Timer Interval Question

I want to call KillZombies every night at midnight. The problem I am facing is that the first timer interval is saved, and not reset to 86400000 milliseconds, as I am trying to do in my method.

Is there a 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 } 
+6
c # timer
source share
4 answers

FWIW, when using timers, I always set the AutoReset property to false . This prevents the timer from starting, so you must call Timer.Start() so that it starts counting again. This will avoid additional Stop() calls.

Also, to be explicit, I would have a function that calculates milliseconds until midnight every time and assigns it to a timer interval each time. Would make your code more understandable. And also, if you use Timer.AutoRest = false , the timer will not start counting until you call Timer.Start() , which means that if you put the Start() call at the end of your KillZombies method, and this method takes 5 seconds to complete, your timer should be 86400000 - 5000 . This 5 second shift will add up over time.

+9
source share

Hmmmm ... I think the problem is planning.

Why not something more suited to scheduling tasks like Quartz.NET ? This way, you donโ€™t have to worry about setting the timer at midnight, and then changing it later.

If you are really against the scope of planning, you can try:

 private void KillZombies(object source, ElapsedEventArgs e) { //Kill zombies Timer.Stop(); Timer.Interval = 86400000; //Milliseconds per 24 hours Timer.Start(); } 
+4
source share

First try calling Stop() , and then Start() retyping it.

+1
source share

Instead of using such a large interval, I would instead use an interval, perhaps one second (or minute), and check DateTime.Now , and if it reaches the desired value, get started.

 System.Timers.Timer Timer = new System.Timers.Timer(); Timer.Elapsed += new ElapsedEventHandler(KillZombies); Timer.Interval = 60000; Timer.Start() private void KillZombies(object source, ElapsedEventArgs e) { if((DateTime.Now - DateTime.Today) < new TimeSpan(0, 1, 0)) { //ToDo: Kill Zombies } } 
+1
source share

All Articles