Possible Duplicate:
Background Worker Check For When It's Midnight?
Is there a SystemEvent which I can register to and which will be published at midnight, when the Date has changed?
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!"); };
The Windows Task Scheduler is generally the proper way to start something at a specified date.
But if you are really searching for an event or equivalent:
var timer = new System.Timers.Timer((DateTime.Today.AddDays(1) – DateTime.Now).
TotalMillisecond);
timer.Elapsed += new ElapsedEventHandler(OnMidnight);
timer.Start();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With