7

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 1
    Your question is a bit unclear about the resolution you want. – H H Sep 16 '09 at 16:25
  • This is the very exact thing I need, its a clear question and I need a clear answer now! Yeah baby! Using a timer is an overkill. – Gary Davies Sep 01 '14 at 00:56

3 Answers3

7

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:

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.

Community
  • 1
  • 1
dtb
  • 213,145
  • 36
  • 401
  • 431
  • 1
    dtb is pretty right in general, but one detail might seem slightly awkward using this approach with 1s interval - it might happen that app starts counting in, say 950ms of each minute. Having system clock in view at the same time with app's one shows a notable delay in switching to the next second. To solve the issue I'd use smaller timer interval, e.g. 100-250ms, depending on particular usage. – Alexey Khoroshikh Aug 20 '15 at 07:31
6

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

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 4
    According to the docs, this fires only when the user changes the system time. This is probably not what CommuSoft wants. Well, or it is, if he wants to find out when the user tampers with the time, as a software protection feature... – OregonGhost Sep 16 '09 at 16:39
4

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);
PhilW
  • 410
  • 4
  • 11