I want to trigger KillZombies every night at midnight.
The problem I’m having is that the first timer interval is retained and not reset to 86400000 milliseconds as I’m trying to do in my method.
Is there any way to remove the old interval and replace it with a new one?
System.Timers.Timer Timer = new System.Timers.Timer();
Timer.Elapsed += new ElapsedEventHandler(KillZombies);
Timer.Interval = MillisecondsToMidnight;
Timer.Start()
private void KillZombies(object source, ElapsedEventArgs e)
{
//Kill zombies
Timer.Interval = 86400000; //Milliseconds per 24 hours
}
FWIW, when using Timers, I always set the
AutoResetproperty tofalse. This prevents the timer from starting up again, so you have to callTimer.Start()to get it to start counting again. This would avoid the extra calls toStop()Also, to be explicit, I would have a function that calculates milliseconds to midnight each time and assign that to the timer’s interval every time. Would make your code more clear. And also, if you use
Timer.AutoRest = false, the timer won’t start counting until you callTimer.Start(), which means if you put theStart()call at the end of yourKillZombiesmethod and that method takes 5 seconds to execute, your timer should then be86400000 - 5000. That 5 second shift would add up over time.