如何使用 .NET Timer 类在特定时间触发事件? [英] How to use the .NET Timer class to trigger an event at a specific time?
问题描述
我希望在我的应用程序中触发一个事件,该事件在白天的某个时间连续运行,例如下午 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
类?
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 执行某些操作,您必须适当地编组代码(例如,在 Windows 窗体应用程序中使用 Control.Invoke
或 Dispatcher.在 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 类在特定时间触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!