3

我正在开发一个每隔 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 分钟执行一次电子邮件发送。

4

1 回答 1

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() {  }
  }
}
于 2012-12-06T13:22:24.553 回答