如何使用.NET Timer类在特定时间触发事件? [英] How to use the .NET Timer class to trigger an event at a specific time?

查看:785
本文介绍了如何使用.NET Timer类在特定时间触发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序时在一定的时间之日其连续运行触发的事件,称下午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.

推荐答案

如何这样的事情,使用<$c$c>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类在特定时间触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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