Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
959 views
in Technique[技术] by (71.8m points)

.net - C# timer getting fired before their interval time

We're getting following problem while using System.Threading.Timer (.NET 2.0) from a Windows service.

  1. There are around 12 different timer objects..
  2. Each timer has due time and interval. This is set correctly.
  3. It is observed that after 3 to 4 hours, the timers start signaling before their interval elapses. For example if the timer is supposed to signal at 4:59:59, it gets signaled at 4:59:52, 7 seconds earlier.

Can someone tell me what is the cause for this behavior and what is the solution for that ?

Thanks, Swati

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Great question... and here's the reason:

"Timing" is a tricky thing when it comes to computers... you can never rely on an "interval" to be perfect. Some computers will 'tick' the timer only every 14 to 15 milliseconds, some more frequently than that, some less frequently.

So:

Thread.Sleep(1);

Could take anywhere from 1 to 30 milliseconds to run.

Instead, if you need a more precise timer - you have to capture the DateTime of when you begin, and then in your timers you would have to check by subtracting DateTime.Now and your original time to see if it is "time to run" your code.

Here's some sample code of what you need to do:

DateTime startDate = DateTime.Now;

Then, start your timer with the interval set to 1 millisecond. Then, in your method:

if (DateTime.Now.Subtract(startDate).TotalSeconds % 3 == 0)
{
    // This code will fire every 3 seconds.
}

That code above will fire faithfully every 3 seconds. You can leave it running for 10 years, and it will still fire every 3 seconds.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...