Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a system-clock-change-tick in C#

Is their a way to execute a delegate or event in C# when the seconds, minutes, hours,... change in the system-clock, without using a timer that checks every millisecond if the property has changed and executes the event with a delay of maximum a millisecond.

I thus want to avoid polling and fire an event at a certain time.

like image 895
Willem Van Onsem Avatar asked Sep 16 '09 16:09

Willem Van Onsem


3 Answers

If your question is: "How do I execute a delegate every full second/minute/hour?"

For minute and hour intervals, you could do something like shown in my answer in this SO question:

  • How to generate event on a specific time of clock in C#?

This should be fairly accurate, but won't be exact to the millisecond.

For second intervals, I'd go with a Timer with a simple 1-second-interval. From a user's perspective I think there's not a lot of difference if the action executes at xx:xx:xx.000 or at xx:xx:xx.350.

like image 75
dtb Avatar answered Oct 07 '22 23:10

dtb


You can subscribe to SystemEvents.TimeChanged. This fires when the system clock is altered.

like image 44
Reed Copsey Avatar answered Oct 07 '22 22:10

Reed Copsey


I solved this in a forms app by setting the interval to (1000 - DateTime.Now.Millisecond)

        _timer1 = new System.Windows.Forms.Timer();
        _timer1.Interval = (1000 - DateTime.Now.Millisecond);
        _timer1.Enabled = true;
        _timer1.Tick += new EventHandler(updateDisplayedTime);

and in the event handler reset the interval to prevent drift.

        <handle event>
        _timer1.Interval = (1000 - DateTime.Now.Millisecond);
like image 4
PhilW Avatar answered Oct 07 '22 22:10

PhilW