2011-01-12 54 views
4

我在Windows服務中有計時器作業,發生錯誤時應該爲其增加間隔。我的問題是我無法獲得timer.Change方法來實際更改間隔。 「DoSomething」始終在初始間隔後調用。在Windows服務中更改計時器間隔

代碼如下:

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 
} 

回答

2

你實際的問題是在這條線:

secondsDefault += secondsIncrementError; 

它應該是:

seconds += secondsIncrementError; 

此外,Timer.Change方法以毫秒爲單位進行操作,所以乘以100顯然是錯誤的。這意味着變化:

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

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

希望它能幫助。

+0

傻我。那很簡單。謝謝! – AyKarsi 2011-01-12 15:01:49

0

嘗試使用stateTimer.Change(0, seconds * 100);這將立即強制System.Threading.Timer以新的時間間隔重新啓動。

+0

試過,但它有相同的效果:( – AyKarsi 2011-01-12 14:55:04