加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 00:04:32 所属栏目:百科 来源:网络整理
导读:我想写一个 Windows服务.但它需要在特定时间运行.例如,我的服务应该每隔5分钟给我发电子邮件. private Timer _timer;private DateTime _lastRun = DateTime.Now;protected override void OnStart(string[] args){ _timer = new Timer(10 * 60 * 1000); // ev
我想写一个 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# Scheduler
> Schedule Windows Service to run twice a week through C# code
> How to schedule windows service in c#?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读