Norgul Norgul - 1 month ago 10
C# Question

C# timer start at exact full second

Is there a way to run the

Timer
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
13:14:15.230
start.

I would like
13:14:15.000
start. Something like:

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


Is that possible?

EDIT:

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

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.

Comments