c# - 如何让我的 Windows 服务以特定的时间间隔运行?

标签 c# windows windows-services

我想写一个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 个类似的问题可能会有所帮助:

这里也有一些很棒的链接:

关于c# - 如何让我的 Windows 服务以特定的时间间隔运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11500877/

相关文章:

c# - 在 C# 中用常量替换硬编码字符串

windows - 消息队列在 Win32 中是如何工作的?

powershell - stop-service cmdlet 可能超时吗?

windows-services - 是否有有关 Windows 服务状态的日志文件?

debugging - 如何调试在 Init() 方法中失败的 Windows 服务

c# - 如何从单个应用程序连接到多个 Oracle Coherence 缓存?

c# - 保存 Word 文档

android - 从 .bat 调用 Gradle 导致批处理执行停止

c++ - 如何在后台进程中处理来自 Windows 任务管理器的 "End Task"?

c# - LINQ 的查询扩展