Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# timer that fires every X seconds, but stays in synch with real time (i.e. with no drift)

Tags:

c#

.net

timer

drift

Is there a .NET Timer available in C# that can ensure there is no "drift" in between events? That is, if you set the timer to go off every X seconds, that after days of operating it won't drift, i.e. to ensure that approach number of X seconds events in a day remains in synch with what it should be?

If not, is there a well known code example that would wrap a Timer function in C# to do this?

like image 973
Greg Avatar asked Jul 21 '10 06:07

Greg


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Why is C named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".


1 Answers

I'm assuming you have tried something already, and that it drifts.

If you want something to fire at say every 5 seconds from the hour (5,10,15,20..), you could set your timer to fire once, then in your callback, reset the timer to fire at DateTime.Now + number of seconds to the next 5 second interval.

This would prevent any drifting as long as your clock is correct.

Something like this

System.Timers.Timer timer = new Timer();

void Init()
{
    timer.Elapsed += timer_Elapsed;
    int wait = 5 - (DateTime.Now.Second % 5);
    timer.Interval = wait*1000;
    timer.Start();
}


void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    timer.Stop();
    int wait = DateTime.Now.Second % 5;
    timer.Interval = wait * 1000;
    timer.Start();
}
like image 158
Mikael Svenson Avatar answered Oct 13 '22 21:10

Mikael Svenson