Norgul
Norgul

Reputation: 4783

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

Upvotes: 1

Views: 1181

Answers (3)

Mahesh Valu
Mahesh Valu

Reputation: 1

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

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

Upvotes: -1

Paul
Paul

Reputation: 11

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.

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 156988

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.

Upvotes: 7

Related Questions