我刚开始开发 Windows 服务。但是我不确定我是否可以在 Onstart()
方法中使用多个计时器?
private System.Timers.Timer timer1;
private System.Timers.Timer timer2;
protected override void OnStart(string[] args)
{
this.timer1 = new System.Timers.Timer(30000); // every 30 seconds
this.timer1.AutoReset = true;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(fonction1);
this.timer1.Start();
this.timer2 = new System.Timers.Timer(10 * 60 * 1000); // every 10 minutes
this.timer2.AutoReset = true;
this.timer2.Elapsed += new System.Timers.ElapsedEventHandler(fonction2);
this.timer2.Start();
}
private void fonction1(object sender, System.Timers.ElapsedEventArgs e)
{
bla bla
}
private void fonction2(object sender, System.Timers.ElapsedEventArgs e)
{
bla bla
}
fonction1
和fonction2
同时运行,但它们的运行间隔不同。它们随后的开始时间不需要同步。在这种情况下,
- 我可以在
OnStart()
方法中使用 2 个计时器吗? - 如果是这样,通常每 30 秒运行一次的
fonction1
是否必须等待fonction2
结束到下一次开始?
我需要在同一 Windows 服务中以不同的时间间隔运行这两种方法。
最佳答案
我不明白为什么不这样做。 System.Timers.Timer
在与 ThreadPool
不同的线程中引发事件,因此它们彼此独立。您唯一需要确保回调中的代码的执行时间不会超过 Interval
。如果您认为它可能发生,您需要在事件处理程序中停止计时器并在最后重新创建它。
private System.Timers.Timer timer1;
protected override void OnStart(string[] args)
{
this.timer1 = new System.Timers.Timer(30000) { AutoReset = false };
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
this.timer1.Start();
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
// Do Work
}
catch (Exception ex)
{
// Logging
}
finally
{
timer1.Start()
}
}
If the SynchronizingObject property is null, the Elapsed event is raised on a ThreadPool thread. If processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. In this situation, the event handler should be reentrant.
https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx
关于C# - Windows 服务中的多个计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36705846/