Norgul Norgul - 11 months ago 69
C# Question

C# timer start at exact full second

Is there a way to run the

so that it starts at exact full second?

stateTimer = new Timer(someCallback, null, 0, 1000);

This one will start right away, repeating each second, but the problem is it will start exactly when I run the program which may result in

I would like
start. Something like:

stateTimer = new Timer(someCallback, null, DateTime.Now.Date, 1000);

Is that possible?


After doing the console log:

Console.WriteLine($"Time: {DateTime.Now.ToString("HH:mm:ss.fff")}");

I've noticed that 1 second interval actually gets incremented by more than one second (about 1,02 each iteration) so after 50 iterations one second is skipped. I have solved my problem by making timer run each 800ms instead. Not ideal solution, but it works, and second never gets skipped (and I have no problem in triggering the same second twice).

stateTimer = new Timer(someCallback, null, 0, 800);

Answer Source

No that is not possible. That would require you to exactly know when the CPU thinks it is a good idea to start to execute your timer code. Even if you would Thread.Sleep for the remaining time, it would still not mean the code is executed at the very millisecond you want to.

Instead, if you just want to do this for formatting, you can use a custom date/time format to do that.