如何使计时器火在经常性地 [英] How to make timer fire in a recurring manner

查看:205
本文介绍了如何使计时器火在经常性地的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我要过期的每次周一下午5点定时器。当测试应用程序,一旦它到达下午5点在周一,我的任务被触发,因为它应该。

I have a timer which I want to expire every Monday at 5pm. When testing the application, as soon as it reaches 5pm on a Monday, my task is fired as it is supposed to.

不过,当我改变系统日期和时间,在接下来的一周下午5时,任务不火。这是我的code:

However, when I change the system date and time to the following week at 5pm, the task does not fire. This is my code:

Timer timer = new Timer(callback, application, timeToEnd, TimeSpan.FromDays(7));

我有一种感觉,它有事可做与 TimeSpan.FromDays(7)部分。任何想法?

推荐答案

您现在的麻烦是。我们要求的框架后, x天,y小时,Z分来通知您。因此,定时器将火完全后,什么时候你告诉它。

You're now in trouble. We asked the framework to notify you after x days, y hours, z minutes. So timer will fire exactly after what time you told it to.

我知道这是不正确的路要走,但是这会工作。

I know this is not the right way to go, but this will work.

SystemEvents.TimeChanged += SystemEvents_TimeChanged;

static void SystemEvents_TimeChanged(object sender, EventArgs e)
{
    timer.Dispose();//Dispose your previous timer
    SetTimerAgain();//Call the method which sets the timer again. you're done
}

我推荐Windows计划任务,但由于某些原因,你不能因此这里是要走的路。

I recommend "Windows Scheduled Tasks", but for some reason you can't so here is the way to go.

你也可以运行一个周期性的定时器作为@giammin建议。

Also you could run a periodic timer as @giammin suggested.

TimerCallback callback = (state) =>
{      
    var now = DateTime.Now; 
    if(now.DayOfWeek == DayOfWeek.Monday 
     && now.TimeOfDay.Hours == 17 && now.TimeOfDay.Minutes == 0)
    {
        MyMethod();
    }
};

Timer timer = new Timer(callback, application, 0, 10000);//10seconds

通过后一种方式,则应该从一次次调用该方法在同一天为自己辩护。

With the latter approach you should defend yourself from calling the method again and again for the same day.

这篇关于如何使计时器火在经常性地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆