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; }
}
Useage: DayChangedNotified.DayChanged += ....
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…