C# event to detect Daylight Saving or even manual time change

人盡茶涼 提交于 2019-11-28 02:08:36

Thank you all for your inputs, they certainly pointed me in the right direction. I was able to solve my issue and I figure to put them here for anyone down the road that find them helpful.

So in my main program where I run the service, it has to be a sub class of ServiceBase.

In my main function I spawned a separate thread as follow:

new Thread(RunMessagePump).Start();

private void RunMessagePump()
{
  Application.Run(new HiddenForm())
}

This Hidden form is exactly what its name say, it is a simple form that is remain hidden by the code this.ResumeLayout(false) under its Intiailaizecomponent() code.

Within this form's FormLoad event you can declare any System event. In my case I have

private void HiddenForm_Load(object sender,EventArgs e)
{
  SystemEvents.timeChanged += new EventHandler(SystemEvents_TimeChanged);
}

Voila, this works out beautifully, and I think I will use this form load event to capture any SystemEvents I want to use down the road.

Cheers.

Well I would strongly suggest not relying on the local time to start with. Use the UTC time of the server, and then if you need to convert that to the local time you can do that wherever you want to, if you know its time zone.

Detecting a manual time change without a useful event is slightly tougher, but could you just run a timer which executes every (say) 30 seconds and checks whether the UTC time isn't "UTC time at least timer tick + 30 seconds" with some amount of tolerance?

You don't need to run it terribly often, so it's not like it's going to be a huge waste of resources. You could always hide this behind an API which can be replaced with a more efficient one if you ever do find a better answer :)

Perhaps less than ideal, you could have an agent running in the foreground that listens for the TimeChanged event and forwards this to your service.

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