The point of this timer is to execute some code whenever it’s midnight.
So basically, the first interval will be between Now and midnight and all intervals following that will be 24hours.
Now that’s all well and good, but I was wondering how this timer business works. Is the MyTimer.Interval recalculated each time the timer resets?
System.Timers.Timer MyTimer = new System.Timers.Timer();
MyTimer.Elapsed += new ElapsedEventHandler(TriggeredMethod);
MyTimer.Interval = [pseudocode]Time between now and midnight[/pseudocode];
MyTimer.Start();
EDIT:
I’m having trouble setting the Interval inside of my TriggerMethod. Where/how should I initiate the Timer so I don’t get any context errors?
private void Form1_Load(object sender, EventArgs e)
{
System.Timers.Timer MyTimer = new System.Timers.Timer();
MyTimer.Elapsed += new ElapsedEventHandler(TriggeredMethod);
MyTimer.Start();
}
private void TriggerMethod(object source, ElapsedEventArgs e)
{
MyTimer.Interval = [pseudocode]Time between now and midnight[/pseudocode];
}
The
Intervalproperty is the number of milliseconds between timer invocations.To run the timer at midnight, you would need to change
Intervalin eachElapsedevent to(int)(DateTime.Today.AddDays(1) - DateTime.Now).TotalMilliseconds.To access the timer inside the
Elapsedhandler, you’ll need to store the timer in a field in your class, like this:Note, by the way, that
System.Timers.Timerwill not fire on the UI thread.Therefore, you cannot manipulate the form inside the
Elapsedhandler.If you need to manipulate the form, you can either switch to
System.Windows.Forms.Timer(which is less accurate) or callBeginInvoke.