我遇到了在時間間隔之前觸發了Elapsed事件的問題。我設置的時間間隔爲10000毫秒,事件將在大約4500毫秒時觸發。我知道這個特定的計時器不是太精確,但我確實知道它比它所顯示的要精確得多。System.Timers.Timer已過期的事件太早觸發
我已檢查以確保沒有多個計時器調用此事件。該解決方案可以在安裝在其上的三臺Windows機器中的兩臺上正常工作。
難道是與.NET版本,CLR版本等
我知道有實現這一點有其他的方式,但我只是在尋找什麼可能會造成這個工作對建議的一個問題3臺服務器中只有2臺。
下面我在服務啓動時創建的計時器只有一次..
checkTimer = new System.Timers.Timer(getSecondsLeft());
checkTimer.Elapsed += checkNowEvent;
checkTimer.AutoReset = true;
checkTimer.Enabled = true;
這裏是用來計算的毫秒數,直到下一分鐘
private double getSecondsLeft()
{
DateTime now = DateTime.Now;
// Has a chance to trigger a few milliseconds before new minute. Added 50ms to interval
return ((60 - now.Second) * 1000 - now.Millisecond) + 50;
}
方法最後是經過的時間事件。
private void checkNowEvent(object sender, ElapsedEventArgs e)
{
try
{
// Stop timer to keep from firing this event again
checkTimer.Enabled = false;
// DOING WORK HERE
}
finally
{
// Set the interval as to tick on the start of the next minute
checkTimer.Interval = getSecondsLeft();
// Start timer again
checkTimer.Enabled = true;
}
}
我只是做這個一些更多的測試,我添加了一些功能,秒錶,看看當它應該是,它看起來像它的時間間隔實際上射擊。然而,當我計算正確的毫秒數到下一分鐘,但它的行爲就好像這個定時器的實現運行速度比系統時鐘快...如果這是有道理的。
這裏是我用來發現的代碼。
private void checkNowEvent(object sender, ElapsedEventArgs e)
{
stopWatch.Stop();
_Log.LogDebug(stopWatch.Elapsed.ToString());
try
{
// Stop timer to keep from firing this event again
checkTimer.Enabled = false;
// DOING WORK HERE
}
catch (Exception ex)
{
// CATCHING EXCEPTIONS HERE IF ANY
}
finally
{
// Set the interval as to tick on the start of the next minute
checkTimer.Interval = getSecondsLeft();
_Log.LogDebug(checkTimer.Interval.ToString());
// Start timer again
checkTimer.Enabled = true;
stopWatch.Reset();
stopWatch.Start();
}
}
在我身邊測試過它,它在每分鐘00秒處滴答滴答。此外,System.Timers.Timer不是很精確,但它比5.5秒更精確 –
在3臺機器上安裝的.NET版本是什麼?這可能是一個開始的好地方。 – Cemafor
與一些信息類似的問題[這裏](http://stackoverflow.com/a/2432601/5095502) – Quantic