'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);


Solution 1:[1]

I had to do something similar in a program that displayed the time and displayed the number of minutes and seconds until the user could do something.

The original code used a 1000 ms timer. This had the problems described by the original poster. I created a thread. The thread had a loop:

private ManualResetEvent myThreadRequestExit = new ManualResetEvent(false);

while (!myThreadRequestExit.WaitOne(1000 - DateTime.UtcNow.Millisecond))
{
    // Do the one-second work here
}

The loop will exit and the thread will terminate when MyThreadRequestExit is set.

Although it may fire a few milliseconds after the start of the second it is close enough that the user perceives the timer as ticking when it should and it does not lose seconds as long as the work can be done in less than a second.

Solution 2:[2]

Just add this line before you start your timer. Sweet and simple :)

Thread.Sleep(1000 - DateTime.Now.Millisecond);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paul
Solution 2 Mahesh Valu