3

I have a task with a trigger:

At 0:00 every day - after triggered, repeat every 1 hours for a duration of 1 day.

And inside my application I read the time this way:

dateTimeUtcNow = DateTime.Now;

And sometimes, very rarely, dateTimeUtcNow shows the time a few milliseconds before full hour like 2015-11-11 14:59:59,914

The server runs on Windows Server 2012 R2, I could accept this on home version but not production.

Why? Is this a bug? How can I prevent this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
kosnkov
  • 5,609
  • 13
  • 66
  • 107
  • Change the trigger for example to 0:01 instead of 0:00? – shurik Nov 17 '15 at 22:19
  • ok I can do it, but why does it happen ? – kosnkov Nov 17 '15 at 22:20
  • 1
    Here is a similar question on SU: [Why is Windows Task Scheduler starting my tasks early?](http://superuser.com/questions/396237/why-is-windows-task-scheduler-starting-my-tasks-early) If I had to guess I'd say it's an issue with the timer accuracy being limited. – mishmash Nov 17 '15 at 22:20
  • @shurik That would make it run late when it works. Best to check that the current time is what you want and reschedule/sleep if need be. – WalterM Nov 17 '15 at 22:20
  • 86 milliseconds is a lot sooner. Is the scheduled task and the receiving app on the same machine? – Shyamal Desai Nov 17 '15 at 22:23
  • If the machine is on a NTP, that might have caused the issue – Shyamal Desai Nov 17 '15 at 22:27
  • I believe it is because Windows operating system is **not** a [Real-time operating system](https://en.wikipedia.org/wiki/Real-time_operating_system) – default Nov 17 '15 at 22:43
  • There's a similar post [here](http://stackoverflow.com/questions/9891879/c-sharp-timer-for-millisecond-waits) that also has an answer. – default Nov 17 '15 at 22:51

1 Answers1

5

Check out Eric Lippert's article on the accuracy, or rather the lack of, of DateTime. Link here.

Key paragraph from the article:

In short, the question “what time is it?” really should only be answered to a level of precision that reflects the level of accuracy inherent in the system. Most computer clocks are not accurately synchronized to even within a millisecond of official time, and therefore precision beyond that level of accuracy is a lie. It is rather unfortunate, in my opinion, that the DateTime structure does surface as much precision as it does, because it makes it seem like operations on that structure ought to be accurate to that level too. But they almost certainly are not that accurate.

If you really need the timer to go off before midnight and not sooner then you will have to force a "slightly" future date/time as has already been suggested in the comments. You do not really have any more control than this.

Paul Sasik
  • 79,492
  • 20
  • 149
  • 189