本文介绍了DateChange的活动在午夜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一个我可以注册的SystemEvent并在日期更改后的午夜发布?
Is there a SystemEvent which I can register to and which will be published at midnight, when the Date has changed?
推荐答案
这是我用来处理此问题的课程。类似于@sll的答案,但是考虑到系统时间的变化,并且还会触发每个午夜,而不是仅触发一次。
Here's a class I use to handle this. It's similar to @sll's answer, however takes into account the system time changing and also will trigger each midnight instead of only once.
static class MidnightNotifier
{
private static readonly Timer timer;
static MidnightNotifier()
{
timer = new Timer(GetSleepTime());
timer.Elapsed += (s, e) =>
{
OnDayChanged();
timer.Interval = GetSleepTime();
};
timer.Start();
SystemEvents.TimeChanged += OnSystemTimeChanged;
}
private static double GetSleepTime()
{
var midnightTonight = DateTime.Today.AddDays(1);
var differenceInMilliseconds = (midnightTonight - DateTime.Now).TotalMilliseconds;
return differenceInMilliseconds;
}
private static void OnDayChanged()
{
var handler = DayChanged;
if (handler != null)
handler(null, null);
}
private static void OnSystemTimeChanged(object sender, EventArgs e)
{
timer.Interval = GetSleepTime();
}
public static event EventHandler<EventArgs> DayChanged;
}
由于它是静态类,因此您可以使用以下代码来订阅事件:
Since it's a static class, you can subscribe to the event using code like:
MidnightNotifier.DayChanged += (s, e) => { Console.WriteLine("It's midnight!"); };
这篇关于DateChange的活动在午夜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!