2012-02-24 73 views
2

我已經在Windows服務中使用System.Threading.Timer當我設置了1分鐘後執行定時器。從12:00:00開始。system.threading.timer無法工作

timer1[timer] = 
    new System.Threading.Timer(timerDelegate, obj, dueTime, interval); 

計時器在此間隔

12:00:00 12時○○分59秒 12時01分00秒 12時02分00秒 12時02分59秒

excuted

,但我想在

12:00:00到EXCUTE12:01:00 12時02分00秒 12:03:00

爲什麼計時器開始在12點〇〇分59秒?

我已經設置了執行剩餘下面的代碼

聲明:

_interval[timer] = interval; 
_startTime[timer] = DATeTime + dueTime; 

計時器回調方法使用

long elapsedMs = Convert.ToInt64((dt - _startTime[timer]).TotalMilliseconds); 
long intervalMs = Convert.ToInt64(_interval[timer].TotalMilliseconds); 
long remainder = elapsedMs % intervalMs; 
if (remainder != 0L) 
{ 
    timer1[timer].Change(
     _interval[timer] - TimeSpan.FromMilliseconds(remainder), 
     _interval[timer]); 
} 

當使用Windows XP中的相同的應用程序它的沃金完美,但在Windows 7 & Windows Server 2008它無法正常工作。

如何解決Threading.Timer中的這個問題?

+1

簡短的回答是:不要使用'Threading.Timer'。這是不準確的。您需要使用高分辨率多媒體計時器。例如,請參閱[本文](http://www.codeproject.com/Articles/5501/The-Multimedia-Timer-for-the-NET-Framework)。 – AVIDeveloper 2012-02-24 13:07:47

+0

它在Windows XP中的工作完美,爲什麼不在Windows 7 – user847455 2012-02-24 13:19:52

+0

也許Win7機器繁忙,而WinXP更加閒置。一個很好的檢查就是將你的WinXP機器與很多進程重疊,看看你的解決方案是否仍然有效。有了多媒體計時器,它會。 – AVIDeveloper 2012-02-24 13:23:23

回答

1

你可能會嘗試System.Timers.Timer - 它對我來說效果很好。爲了方便起見,我用代理粘貼了一個靜態定時器類:

public static class Timer 
    { 
     private static System.Timers.Timer _timer = new System.Timers.Timer(); 
     public static void start(bool enabled, int interval) 
     { 
      _timer = new System.Timers.Timer(); 
      _timer.Elapsed += new ElapsedEventHandler(_timerElapsed); 
      _timer.Enabled = enabled; 
      _timer.Interval = interval; 
     } 
     static void _timerElapsed(object sender, ElapsedEventArgs e) 
     { 
      OnTimedEvent(sender, e);     
     } 
    } 
+1

'System.Timers.Timer'在內部使用'System.Threading.Timer',所以我認爲它不會解決OP有任何問題。 – svick 2012-03-14 00:38:10

+0

爲什麼這項工作只能在本地測試?當我部署到生產服務器時,它什麼都不做,它會發生嗎? – 2013-01-10 19:34:54