System.Timers.Timer gradually increasing interval?

I have been facing a very unique problem. I am using a System.Timers.Timer which triggers a method every minute. Gradually, I came to know the time interval is not constant.

For testing and ensuring the issue, i just run a timer which elapsed a function every minute. And the output was shocking, the timer interval seconds are not constant. They are changing thus so creating an issue.

12/13/2016 3:39:26 PM
12/13/2016 3:40:25 PM
12/13/2016 3:41:25 PM
12/13/2016 3:42:25 PM
12/13/2016 3:43:25 PM
12/13/2016 3:44:26 PM
12/13/2016 3:45:26 PM
12/13/2016 3:46:26 PM
12/13/2016 3:47:26 PM
12/13/2016 3:48:26 PM
12/13/2016 3:49:26 PM
12/13/2016 3:50:26 PM
12/13/2016 3:51:26 PM

As one can notice the interval is gradually increasing. The problem occurs when days expend. Thus so issue is creating like I have to process within the minute and the date is changed.

The code is simple

System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 60000;
timer.Elapsed += timer_Elapsed;
timer.Start();

System.Timers.Timer is not that precise. Check the remarks section here.


I managed to resolve that issue. The solution is simple as

Set two checks at global level;

static bool _IsDirty = false, _TimerChecked = true;

Then handle the logic inside the ElapsedEventHandler as let DataSynchronizer is the delegate method then implementation could be as

private Task AdwordsPullDataSynchronizer(System.Timers.Timer timer)
{

     if (!_TimerChecked)
     {
          _IsDirty = false;
          timer.Stop();
          var interval = Convert.ToDouble(Math.Abs(DateTime.Now.Second - 60));
          timer.Interval = (interval + 2) * 1000;
          timer.Start();
          _TimerChecked = true;
     }

     if (DateTime.Now.Second > 10)
     {
         _IsDirty = true;
         _TimerChecked = false;
     }


     //Place your interval logic here

     if (_IsDirty)
     {
        timer.Stop();
        var interval = Convert.ToDouble(Math.Abs(DateTime.Now.Second - 60));
        timer.Interval = (interval + 2) * 1000;
        timer.Start();
     }

     return Task.FromResult(0);
}

Pretty clear save side logic i have implemented.

What the code is doing is? It will check if the interval seconds greater than 10 then it will reset the timer and set the interval to next ElapsedEvent 2nd second . Then it will reset and fixed the interval to every ElapsedEvent 2nd second .

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

上一篇: 用CSS创建菜单并溢出:auto

下一篇: System.Timers.Timer逐渐增加间隔?