Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect if the system time is changed? (from .net)

Tags:

.net

time

windows

I am using DateTime.UtcNow to measure time in my software and need to be able to tell if “action a” happens less more than 10 seconds after “action b”

However what if the system time is change? So how I do I detect if the system time is changed?

I don’t wish to use a stopwatch as we need to run on servers with more then one CPU, see http://kristofverbiest.blogspot.com/2008/10/beware-of-stopwatch.html

I also need to cope with virtual machines being paused and restarted, so the “tick count” is unlikely to be useful to me.

like image 655
Ian Ringrose Avatar asked Nov 22 '10 15:11

Ian Ringrose


1 Answers

You can use the SystemEvents.TimeChanged event to detect the time changed. However, this will only fire if you have a messagepump running - this is fine for windows client applications, but not so much for most server applications (like services, web apps, etc).

Otherwise you can use Environment.TickCount - it doesn't have excellent resolution, but if your "10" seconds can be "nearly 10 seconds" you're probably fine. A far as the VM limitation, note that TickCount rolls over when the machine has been up long enough, so you'll have to handle that, possibly with a DateTime.UtcNow sanity check either way.

I'd use the combination of both - but note that there's no absolutely accurate way other than checking some external timeserver that is known accurate (which is going to have perf impact) that will work in the VM case anyway... make sure you determine what is "reliable enough" before you spend more time than the issue is worth.

like image 130
Philip Rieck Avatar answered Sep 19 '22 23:09

Philip Rieck