我想写一个windows服务。但它需要在特定时间运行。例如,我的服务应每 5 分钟向我发送一次电子邮件。
private Timer _timer;
private DateTime _lastRun = DateTime.Now;
protected override void OnStart(string[] args)
{
_timer = new Timer(10 * 60 * 1000); // every 10 minutes
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
//...
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// ignore the time, just compare the date
if (_lastRun.Date < DateTime.Now.Date)
{
// stop the timer while we are running the cleanup task
_timer.Stop();
//
// do cleanup stuff
//
_lastRun = DateTime.Now;
_timer.Start();
}
}
我希望我的服务每 5 分钟给我发一次电子邮件。
最佳答案
好吧,我看到另一个讨论 windows service vs scheduled task 的问题还有this .所以你可能想看看除此之外的其他问题,这里有 2 个类似的问题可能会有所帮助:
- How might I schedule a C# Windows Service to perform a task daily?
- How to schedule a C# Windows Service to run a method daily?
这里也有一些很棒的链接:
关于c# - 如何让我的 Windows 服务以特定的时间间隔运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11500877/