后台工作者检查是否是午夜? [英] Background Worker Check For When It's Midnight?
本文介绍了后台工作者检查是否是午夜?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为WinForm创建一个后台工作程序,每当午夜过去时都会触发代码.
I want to create a background worker for a WinForm that triggers code whenever midnight rolls by.
我对操作方法有所了解,但我敢肯定这不是最好的方法.
I have an idea of how to do it, but I'm pretty sure it's not the best way to do it.
while(1==1)
{
//if Datetime.Now == midnight, execute code
//sleep(1second)
}
推荐答案
使用System.Timers.Timer
,在应用程序启动时,只需计算DateTime.Now
和DateTime.Today.AddDays(0)
之间的差即可.然后设置该时间间隔.
Use a System.Timers.Timer
and at application start up just calculate the difference between DateTime.Now
and DateTime.Today.AddDays(0)
. Then set the interval for that amount.
我最近实际上做了这样的事情:
I actually did something just like this recently:
public static class DayChangedNotifier
{
private static Timer timer;
static DayChangedNotifier()
{
timer = new Timer(GetSleepTime());
timer.Elapsed += (o, e) =>
{
OnDayChanged(DateTime.Now.DayOfWeek);
timer.Interval = this.GetSleepTime();
};
timer.Start();
SystemEvents.TimeChanged += new EventHandler(SystemEvents_TimeChanged);
}
private static void SystemEvents_TimeChanged(object sender, EventArgs e)
{
timer.Interval = GetSleepTime();
}
private static double GetSleepTime()
{
var midnightTonight = DateTime.Today.AddDays(1);
var differenceInMilliseconds = (midnightTonight - DateTime.Now).TotalMilliseconds;
return differenceInMilliseconds;
}
private static void OnDayChanged(DayOfWeek day)
{
var handler = DayChanged;
if (handler != null)
{
handler(null, new DayChangedEventArgs(day));
}
}
public static event EventHandler<DayChangedEventArgs> DayChanged;
}
AND:
public class DayChangedEventArgs : EventArgs
{
public DayChangedEventArgs(DayOfWeek day)
{
this.DayOfWeek = day;
}
public DayOfWeek DayOfWeek { get; private set; }
}
用法:DayChangedNotified.DayChanged += ....
这篇关于后台工作者检查是否是午夜?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文