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?

4

1 回答 1

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.

于 2015-11-17T22:26:51.373 回答