Change timer interval in windows service

I have a timer job inside a windows service for which the interval should increase if errors occur. My problem is that I cannot get a timer. Modify the method to actually change the interval. "DoSomething" is always called after the start interval.

Code follows:

protected override void OnStart(string[] args) { //job = new CronJob(); timerDelegate = new TimerCallback(DoSomething); seconds = secondsDefault; stateTimer = new Timer(timerDelegate, null, 0, seconds * 1000); } public void DoSomething(object stateObject) { AutoResetEvent autoEvent = (AutoResetEvent)stateObject; if(!Busker.BitCoinData.Helpers.BitCoinHelper.BitCoinsServiceIsUp()) { secondsDefault += secondsIncrementError; if (seconds >= secondesMaximum) seconds = secondesMaximum; Loggy.AddError("BitcoinService not available. Incrementing timer to " + secondsDefault + " s",null); stateTimer.Change(seconds * 100, seconds * 100); return; } else if (seconds > secondsDefault) { // reset the timer interval if the bitcoin service is back up... seconds = secondsDefault; Loggy.Add ("BitcoinService timer increment has been reset to " + secondsDefault + " s"); } // do the the actual processing here } 
+4
source share
2 answers

Your current problem on this line:

 secondsDefault += secondsIncrementError; 

It should be:

 seconds += secondsIncrementError; 

In addition, the Timer.Change method works in miliseconds, so multiplying by 100 is obviously wrong. This means a change:

 stateTimer.Change(seconds * 100, seconds * 100); 

For

 stateTimer.Change(seconds * 1000, seconds * 1000); 

Hope this helps.

+2
source

Try using stateTimer.Change(0, seconds * 100); , this will immediately cause System.Threading.Timer restart at a new interval.

0
source

Source: https://habr.com/ru/post/1335257/


All Articles