views:

347

answers:

4

I'm looking at using a System.Timers.Timer in a windows service. I would like to know how reliable and accurate they are. In particular:

  1. Are there any guarantees about how often they will run?
  2. What happens when the processor or memory are overloaded? Will the ElapsedEventArgs.SignalTime always be accurate under such circumstances?
  3. If a timer is run for a long time, what happens when corrections are made to the system time to take into account inaccuracies in the system clock?

Update: Thanks for the answers so far. I was hoping to get more specific answers to the three issues that I detailed in my original question.

A: 

I use a sleeping(Thread.Sleep(int)) value while in a loop for my windows service tasks. This way you can implement calculations for how much you want to sleep if it's not interval based but specific time based. Never had a problem with this approach.

Konstantinos
Thread.Sleep has the same resolution limitations of an standard timer, meaning the OS does not guarantee real time precision for it, and therefore the same question remains, what's the precision of the standard timer or the thread.sleep method?
Jorge Córdoba
+1  A: 

From my experience I can tell timers may get out of sync if you have a very high performance load.

Holli
+1  A: 

If you need a very high performance clock in .NET, you should check out System.Diagnostics.Stopwatch. It uses the kernel timer in windows to measure time very precisely. Its generally intended for diagnostic purposes, such as measuring the elapsed execution time for a given piece of code...but it could probably be wrapped in a custom high performance Timer class for scheduled events if need be.

jrista
+2  A: 

What is accurate for you? Normal windows timer has accurancy of about 100Hz. If you want something more accurate, take a look at QueryPerformanceTimer (System.Diagnostics.Stopwatch uses it). It is great and very accurate for short time spans, but as CPU frequency changes (power management), it will get out of sync.

Also, I have seen system clock drift for minutes a day, so we had to install NTP utility and schedule it (the irony) to run periodically .

Basically, we never acheived submillisecond time accurancy on windows machine, even with some tries to use main clock as baseline and QuerperformanceTimer as sort of differential timer. Never worked right.

bh213