C # that fires every X seconds, but synchronizes with real time (i.e. no drift)

Is there a C # .NET Timer that can guarantee that there is no "drift" between events? That is, if you set a timer for every X seconds, that after several days of operation, it does not drift, that is, to ensure that the number of calls of X seconds during the day remains in sync with what should be?

If not, is there a well-known code example that would wrap the timer function in C # for this?

+7
c # timer
source share
2 answers

Sorry for the link to quartz.net , but this is a fully functional, corporate, tested ... library ... you don’t need to reinvent the wheel :)

If you are worried about overhead, what is your definition of overhead? this is the file size (binary files about 0.5 MB) or the overhead in the logic. well for the logical part: I think that implementing their IJob -interface does a good job of getting better consumer code. I am not such a great friend of built-in methods (as an example, since you can run your pointers on a timer) - classes will give you much more features, and once again we will make oop, domain-design, ...

but: doing Console.WriteLine(...) with quartz.net would be superfluous ... :)

+6
source share

I assume that you have already tried something, and that it is drifting.

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

This will prevent any drift while your watch is correct.

Something like that

 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(); } 
+15
source share

All Articles