How to change the time interval in System.Threading.Timer from the callback function of this timer?

How to change the interval in System.Threading.Timer from the callback function of this timer? Is it correct?

Doing so. Did not happen.

public class TestTimer { private static Timer _timer = new Timer(TimerCallBack); public void Run() { _timer.Change(TimeSpan.Zero, TimeSpan.FromMinutes(1)); } private static void TimerCallBack(object obj) { if(true) _timer.Change(TimeSpan.Zero, TimeSpan.FromMinutes(10)); } } 
+7
source share
2 answers

This line generates infinite recursion:

 if(true) _timer.Change(TimeSpan.Zero, TimeSpan.FromMinutes(10)); 

The first parameter causes TimerCallBack to execute immediately. Therefore, he performs it again and again indefinitely.

The fix will be

 if(true) _timer.Change(TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10)); 
+8
source

The problem is that your Change call indicates that the next call should happen immediately. If you are going to call Change every time, you can simply use the Timeout.Infinite period (which is only a constant of -1) to say to avoid repeating altogether after the next time - but it will continue to fire, because the next time you reset his. For example:

 using System; using System.Threading; static class Program { private static Timer timer = new Timer(TimerCallBack); public static void Main() { timer.Change(TimeSpan.Zero, TimeSpan.FromSeconds(1)); Thread.Sleep(10000); } private static void TimerCallBack(object obj) { Console.WriteLine("{0}: Fired", DateTime.Now); timer.Change(TimeSpan.FromSeconds(3), TimeSpan.FromMilliseconds(Timeout.Infinite)); } } 

Alternatively, you can change it only once, and then leave it:

 using System; using System.Threading; static class Program { private static Timer timer = new Timer(TimerCallBack); private static bool changed = false; public static void Main() { timer.Change(TimeSpan.Zero, TimeSpan.FromSeconds(1)); Thread.Sleep(10000); } private static void TimerCallBack(object obj) { Console.WriteLine("{0}: Fired", DateTime.Now); if (!changed) { changed = true; TimeSpan interval = TimeSpan.FromSeconds(3); timer.Change(interval, interval); } } } 

Note that nothing uses the start interval (1 second in the above samples) anyway, because we call Change immediately - if you really want a different time before the first call, do not use TimeSpan.Zero in the Change start call.

+4
source

All Articles