【发布时间】:2014-05-27 10:44:21
【问题描述】:
我有一个如下定义的计时器。计时器执行一个长时间运行的任务。我遇到的问题是当计时器运行时,间隔再次过去,另一个计时器执行开始,即_timer_Elapsed。定时器完成后如何让定时器执行一个间隔。现在的方式可能会同时执行多个计时器,这会导致我的代码出现各种问题。
protected override void OnStart(string[] args)
{
_timer = new System.Timers.Timer();
_timer.AutoReset = false;
_timer.Interval = (Convert.ToInt32(ConfigurationManager.AppSettings["CheckInterval"]));
_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = true;
_timer.Start(); // Start timer
}
public static void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
_timer.Interval = (Convert.ToInt32(ConfigurationManager.AppSettings["CheckInterval"]));
BLLGenericResult SystemCheckItems_Result = ServiceItemOperations.CheckItems(); // Long Running Task
}
catch (Exception ex)
{
// Exception handling...
}
finally
{
_timer.Start();
}
}
【问题讨论】:
-
这是不可能的,使用 AutoReset = false 确保计时器不会再次触发,除非您明确重新启用它。您很可能会以错误的方式进行操作,例如在 Elapsed 事件处理程序的开头而不是结尾重新启用它。或者没有正确实现 OnStop() 方法。
-
@HansPassant 是的 - 我也在读这个 - 让我提出我的 _Timer_Elapsed 方法,看看你的想法
-
或者...您再次调用了 OnStart 函数,并且除了前一个仍在运行的计时器之外,还启动了一个新计时器。
-
@SteveWellens 我不这么认为 - OnStart 只调用一次 - 在 Windows 服务启动时
-
将间隔分配也移到底部。又一个 System.Timers.Timer 怪癖。
标签: c# timer system.timers.timer