2016-03-08 49 views
1

我遇到了在時間間隔之前觸發了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(); 
     } 
    } 
+1

在我身邊測試過它,它在每分鐘00秒處滴答滴答。此外,System.Timers.Timer不是很精確,但它比5.5秒更精確 –

+0

在3臺機器上安裝的.NET版本是什麼?這可能是一個開始的好地方。 – Cemafor

+0

與一些信息類似的問題[這裏](http://stackoverflow.com/a/2432601/5095502) – Quantic

回答

1

在新分鐘之前發射的原因是由於系統時間有問題。 DateTime.Now返回正確的毫秒數,直到下一分鐘,但系統時間移動非常緩慢。計時器實現似乎正常工作,因爲我使用秒錶進行了驗證。我只是將系統時間與另外兩臺工作電腦同步,而不是,但是5分鐘後,再次慢了幾分鐘。

+0

http://www.sevenforums.com/performance-maintenance/289471-system- clock-going-slow.html這可能有所幫助 – Cemafor