我在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
}
答案 0 :(得分:2)
你的实际问题在于这一行:
secondsDefault += secondsIncrementError;
应该是:
seconds += secondsIncrementError;
此外,Timer.Change
方法以毫秒为单位运行,因此乘以100显然是错误的。这意味着改变:
stateTimer.Change(seconds * 100, seconds * 100);
要
stateTimer.Change(seconds * 1000, seconds * 1000);
希望它有所帮助。
答案 1 :(得分:0)
尝试使用stateTimer.Change(0, seconds * 100);
这会立即强制System.Threading.Timer
以新的间隔重新启动。