C# 在c中,每x秒执行一次操作,持续y分钟#
我需要每5秒运行一个函数,持续10分钟C# 在c中,每x秒执行一次操作,持续y分钟#,c#,timer,C#,Timer,我需要每5秒运行一个函数,持续10分钟 我使用计时器运行5秒,但如何将计时器限制为10分钟?timer.Stop()。在每次通话中,测试currentTime+5秒>startTime+10分钟。如果是,请禁用计时器 我更喜欢这种方法,而不是只运行N个时钟,因为计时器不能保证在您希望的时候启动。120个滴答声可能会在10分钟的真实时间内运行。只需使用DateTime变量来跟踪它应该何时结束,并在开始之前将其设置为正确。在已用事件处理程序上,检查信号时间是否小于结束时间。如果没有,请停止计时器。您
我使用计时器运行5秒,但如何将计时器限制为10分钟?
timer.Stop()。在每次通话中,测试currentTime+5秒>startTime+10分钟。如果是,请禁用计时器
我更喜欢这种方法,而不是只运行N个时钟,因为计时器不能保证在您希望的时候启动。120个滴答声可能会在10分钟的真实时间内运行。只需使用DateTime变量来跟踪它应该何时结束,并在开始之前将其设置为正确。在已用事件处理程序上,检查信号时间是否小于结束时间。如果没有,请停止计时器。您可以计算调用函数的次数,并创建减量计数器,然后取消订阅计时器计时。或者,您可以运行另一个计时器,该计时器的刻度周期为10分钟,在刻度上,您可以取消订阅调用函数的计时器刻度。将Y分钟除以X间隔,以获得需要运行的次数。之后,您只需要计算函数被调用的次数
在您的情况下,10分钟=600秒/5秒=需要120个呼叫。只需要一个计数器,记录函数被调用的次数。让计时器循环如下:
DateTime endTime = DateTime.Now.AddMinutes(10);
while(endTime < DateTime.Now)
{
// Process loop
}
DateTime endTime=DateTime.Now.AddMinutes(10);
while(endTime
您可以设置两个计时器,一个运行5秒,另一个运行10分钟,然后禁用第一个计时器只需从已用处理程序中捕获要停止和结束计时器的时间。下面是一个示例(注意:我使用了一个System.Threading.Timer
Timer
。为您正在做的事情选择合适的计时器。例如,如果您在Winforms中编写,您可能在System.Windows.Forms.Timer
之后。)
您可以使用第二个计时器:
class Program
{
static void Main(string[] args)
{
int interval = 5 * 1000; //milliseconds
int duration = 10 * 60 * 1000; //milliseconds
intervalTimer = new System.Timers.Timer(interval);
durationTimer = new System.Timers.Timer(duration);
intervalTimer.Elapsed += new System.Timers.ElapsedEventHandler(intervalTimer_Elapsed);
durationTimer.Elapsed += new System.Timers.ElapsedEventHandler(durationTimer_Elapsed);
intervalTimer.Start();
durationTimer.Start();
}
static void durationTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
intervalTimer.Stop();
durationTimer.Stop();
}
static void intervalTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//call your method
}
private static System.Timers.Timer intervalTimer;
private static System.Timers.Timer durationTimer;
}
我宁愿存储结束时间,并在每次迭代之前将其与当前时间值进行比较。然而,+1.对简单答案的否定之爱?:)
class Program
{
static void Main(string[] args)
{
int interval = 5 * 1000; //milliseconds
int duration = 10 * 60 * 1000; //milliseconds
intervalTimer = new System.Timers.Timer(interval);
durationTimer = new System.Timers.Timer(duration);
intervalTimer.Elapsed += new System.Timers.ElapsedEventHandler(intervalTimer_Elapsed);
durationTimer.Elapsed += new System.Timers.ElapsedEventHandler(durationTimer_Elapsed);
intervalTimer.Start();
durationTimer.Start();
}
static void durationTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
intervalTimer.Stop();
durationTimer.Stop();
}
static void intervalTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//call your method
}
private static System.Timers.Timer intervalTimer;
private static System.Timers.Timer durationTimer;
}