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

∥☆過路亽.° 提交于 2019-12-05 08:45:40
dtb

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.

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

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!