There are many questions about C# System.Threading.Timer
on SO, but I cannot find this exact question.
In our code, we need to ensure that a timer fires after, and I mean after, a given amount of time. If the timer fires .00001 seconds early, then that's bad. On the other hand, if the timer fires even a few seconds late, that's OK.
I made this dotnetfiddle to show that the timer sometimes fires early. Run it a few times and you'll see it (or increase numSamples
in the code). On my local PC, I've checked other time spans and they behave similarly, but dotnetfiddle doesn't allow your code to execute too long so TimeSpan.FromSeconds(1)
is what's in that demo.
One hack-ish way I've thought is to just sleep for a tenth of a second and that seems to catch the fuzzy-ness around Timer
's inaccuracy. Is there a canonical way to make sure that a time actually fires after a given time? I know there are more accurate timers in C#, but since our requirements allow for some wiggle room after the due time I figured there might be something cheaper that I've overlooked.
Thanks to @PaulF and @AlexeiLevenkov for your comments. I think I fell victim to the XY problem. My main concern was that the underlying "ground truth" for the time in the code I'm working in is DateTime
's time. Trying to have an accurate timer with respect to an inaccurate "ground truth" is flawed. I gave the answer I came up with below, and will accept it in the future.