Ben*_*ein 11
这是我用来处理这个问题的一个类.它类似于@sll的答案,但考虑到系统时间的变化,也会触发每个午夜而不是一次.
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;
}
Run Code Online (Sandbox Code Playgroud)
由于它是静态类,您可以使用以下代码订阅事件:
MidnightNotifier.DayChanged += (s, e) => { Console.WriteLine("It's midnight!"); };
Run Code Online (Sandbox Code Playgroud)