在固定的时间间隔后重新启动Windows服务

时间:2012-12-06 12:52:56

标签: c# windows service timer

我正在开发一个每15分钟发送一次自动电子邮件的Windows服务。我使用计时器在固定的时间间隔(15分钟)后再次使用该服务,但它不起作用。

namespace Mailer
{
  public partial class Mailer : ServiceBase
  {
    System.Timers.Timer createOrderTimer;
    public Mailer()
    {
      InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
      sendmail();  //function to send email.

      createOrderTimer = new System.Timers.Timer();                      
      createOrderTimer.Elapsed += new  System.Timers.ElapsedEventHandler(createOrderTimer_Elapsed);
      createOrderTimer.Interval = 15000;
      createOrderTimer.Enabled = true;
      createOrderTimer.AutoReset = true;                      
      createOrderTimer.Start();
    }

    protected void createOrderTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs args)
    {
      createOrderTimer.Stop();
      ServiceController controller = new ServiceController("Mailer");
      controller.Start();
    }

    protected void sendmail
    {
      //code to send email.
    }

    protected override void OnStop() {  }
  }
}

最初发送电子邮件但我希望每15分钟发送一次电子邮件。

1 个答案:

答案 0 :(得分:2)

您需要更改此类代码

namespace Mailer
{
  public partial class Mailer : ServiceBase
  {
    System.Timers.Timer createOrderTimer;
    public Mailer()
    {
      InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
      createOrderTimer = new System.Timers.Timer();                      
      createOrderTimer.Elapsed += new  System.Timers.ElapsedEventHandler(sendmail);
      createOrderTimer.Interval = 900000; // 15 min
      createOrderTimer.Enabled = true;
      createOrderTimer.AutoReset = true;                      
      createOrderTimer.Start();
    }

    protected void sendmail(object sender, System.Timers.ElapsedEventArgs args)
    {
      //code to send email.
    }

    protected override void OnStop() {  }
  }
}