Incorrect elapse time for System.Timers.Timer

Possible Duplicate:
System.Timer elapsed event seems to fire late for short intervals in .Net

I use System.Timers.Timer in my windows service. Interval set to 60000 ms, but every next elapse, timer interval increases on some ms..Here example of log:

2011-09-05 00:00:37,177 [80] INFO - 
timer_Elapsed;

2011-09-05 00:01:37,187 [8] INFO  - 
timer_Elapsed;

2011-09-05 01:24:38,279 [71] INFO   - 
timer_Elapsed;

But I need to elapse timer in 37 seconds, as example, but after work some time, we have elapse timer in 38, 39, 40 .. sec..

I don't need very precision timer, but i need to elapse 37 +- 1sec every time..

How i can resolve this problem???


I one time set Interval property in:

protected override void OnStart(string[] args)
{
   log4net.Config.XmlConfigurator.Configure();
   EmailReminderService.Logger.Info("Service started");

   _timer.Interval =Convert.ToInt32(ConfigurationManager.AppSettings["Interval"]);
   _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
   _timer.Enabled = true;               
}

private void timer_Elapsed(object source, System.Timers.ElapsedEventArgs e)
{
   EmailReminderService.Logger.Info("timer_Elapsed;");
   EmailReminderManager manager = new EmailReminderManager();
   manager.EmailReminderProcessing();
}

In timer elapsed method not use _timer object..


On each iteration calculate how the time difference between now and the point in time where you want to trigger the next timer. Then set your interval to that value. This will prevent a drift.

//Once
DateTime start=DateTime.UtcNow;// Or if you prefer that the event
                               // happens on the same second no matter when
                               // the program started you can simply
                               // use a constant here

//At the end of the timer handler
int interval=(int)((DateTime.UtcNow-start).TotalSeconds*1000);
const int targetInterval=60000;
interval(interval+targetInterval/2)%targetInterval+targetInterval/2;
timer.Interval=interval;

This chooses an interval between 30 and 90 seconds so that you will hit the target time exactly.

The program deals gracefully with UtcNow<start since that may happen when the user changes the system clock.


we have elapse timer in 38, 39, 40 .. sec..

Are you sure you aren't doing something with the Interval property of your timer? It may vary since you aren't working on a Real-time OS, but a second being added every call sounds more like a bug on your side than in the Timer .

链接地址: http://www.djcxy.com/p/63010.html

上一篇: 处理返回Timer的方法

下一篇: System.Timers.Timer的过去时间不正确