我想在我的应用程序时在一定的时间之日其连续运行触发的事件,称下午4:00。我想过运行计时器每一秒,当时间等于下午4:00运行事件。这样可行。但我不知道是否有一种方法在下午4:00到刚刚拿到回调一次,不必继续检查。
I would like to have an event triggered in my app which runs continuously during the day at a certain time, say at 4:00pm. I thought about running the timer every second and when the time is equal to 4:00pm run the event. That works. But I'm wondering if there's a way to just get the callback once at 4:00pm and not having to keep checking.
推荐答案如何这样的事情,使用System.Threading.Timer上课吗?
How about something like this, using the System.Threading.Timer class?
var t = new Timer(TimerCallback); // Figure how much time until 4:00 DateTime now = DateTime.Now; DateTime fourOClock = DateTime.Today.AddHours(16.0); // If it's already past 4:00, wait until 4:00 tomorrow if (now > fourOClock) { fourOClock = fourOClock.AddDays(1.0); } int msUntilFour = (int)((fourOClock - now).TotalMilliseconds); // Set the timer to elapse only once, at 4:00. t.Change(msUntilFour, Timeout.Infinite);请注意,如果您使用 System.Threading.Timer ,由 TimerCallback 指定的回调将被执行的一个线程池(非UI)线程,所以如果你在4:00做你的UI策划的东西,你就会有code恰当(例如,使用元帅控制.Invoke 在Windows窗体应用程序,或 Dispatcher.Invoke 在一个WPF应用程序)。
Note that if you use a System.Threading.Timer, the callback specified by TimerCallback will be executed on a thread pool (non-UI) thread—so if you're planning on doing something with your UI at 4:00, you'll have to marshal the code appropriately (e.g., using Control.Invoke in a Windows Forms app, or Dispatcher.Invoke in a WPF app).
更多推荐
如何使用.NET Timer类在特定时间触发事件?
发布评论