Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, System.Timers.Timer, run every min in sync with system clock

I am trying to get a timer run every minute in sync with the system clock (00:01:00, 00:02:00, 00:03:00, etc). Will the following code produce a stable timer? I've tried running it. The timer does precisely run every min. But the question is will it start to wander off, say, after several months?

private System.Timers.Timer timer;

public frmMain()
{
            timer = new System.Timers.Timer();
            timer.AutoReset = false;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            timer.Interval = GetInterval();
            timer.Start();
}

private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
            //Do processing

            timer.Interval = GetInterval();
            timer.Start();

}
private double GetInterval()
{
            DateTime now = DateTime.Now;
            return ((60 - now.Second) * 1000 - now.Millisecond);
}
like image 817
user1437139 Avatar asked Oct 23 '25 15:10

user1437139


1 Answers

It won't.

DateTime.Now uses the system clock as the reference timer, so your timer will always stay in sync with it, modulus the few milliseconds of system clock resolution.

like image 92
user703016 Avatar answered Oct 25 '25 05:10

user703016



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!