[英]Change timer interval in windows service
我在Windows服務中有計時器作業,當發生錯誤時,應該增加其間隔。 我的問題是我無法獲取timer.Change方法來實際更改間隔。 始終在初始間隔之后調用“ DoSomething”。
代碼如下:
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
}
您的實際問題在以下行中:
secondsDefault += secondsIncrementError;
它應該是:
seconds += secondsIncrementError;
此外, Timer.Change
方法以毫秒為Timer.Change
運行,因此乘以100顯然是錯誤的。 那意味着改變:
stateTimer.Change(seconds * 100, seconds * 100);
至
stateTimer.Change(seconds * 1000, seconds * 1000);
希望能幫助到你。
嘗試使用stateTimer.Change(0, seconds * 100);
這將立即迫使System.Threading.Timer
以新的間隔重新啟動。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.