C# - Windows 服务中的多个计时器

标签 c# asp.net timer windows-services

我刚开始开发 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
        }

fonction1fonction2 同时运行,但它们的运行间隔不同。它们随后的开始时间不需要同步。在这种情况下,

  1. 我可以在 OnStart() 方法中使用 2 个计时器吗?
  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/

相关文章:

asp.net - 使用 ASP.NET 网络服务帐户访问网络文件夹

asp.net - Web API 路由 - api/{controller}/{action}/{id} "dysfunctions"api/{controller}/{id}

c# - 多个 kestrel 无状态服务实例在服务结构中的不同端口上运行

c# - 帮我 XOR 加密

c# - If/Else OR "? :"(条件)不工作

C 中的跨平台高分辨率计时器?

c# - 是否可以在数据库中保存正在运行的计时器?

c# - .NET Framework 4.5 或更高版本中的 AccessViolationException

c# - 信箱不可用。服务器响应为 : 5. 4.1 中继访问被拒绝

c - 内核模块计时器杀死系统