.NET Timers, they start at the exact interval or after processing + interval

So, a fairly simple question.

How exactly does the interval work for System.Timers?

Does it eliminate 1 second, every second, regardless of how long it takes to wait, or does it require the first procedure to complete, and then restarts the interval?

So either:

  • 1 sec .... 1 sec .... 1 sec, etc.
  • 1 s + process time .... 1 s + process time ... 1 s + process time, etc.

The reason I'm asking about this is because I know that my โ€œprocessingโ€ takes a lot less than 1 second, but I would like to run it every second on a point (or as close as possible).

I used the Thread.Sleep method, for example:

Thread.Sleep(1000 - ((int)(DateTime.Now.Subtract(start).TotalMilliseconds) >= 1000 ? 0 : (int)(DateTime.Now.Subtract(start).TotalMilliseconds))); 

When the start time is recorded at the beginning of the procedure. The problem here is that Thread.Sleep only works in milliseconds . Thus, my program may restart at intervals of 1000 ms or to some extent, for example, 1000.0234ms, which may happen because one of my routines takes 0ms according to "TimeSpan", but obviously it used ticks / nanoseconds, which then it would mean that time is off and no longer every second. If I could sleep in ticks or nanoseconds, it would be hard.

If number 1 applies to System.Timers, then I think I'm sorted. If not, I need some way to "streamline" the stream to a higher time resolution ie ticks / nanoseconds.

You may ask why I do the built-in IF statement, but sometimes processing can exceed 1000 ms, so we need to make sure that we do not create the minus digit. In addition, by the time we determine this, the end time has changed a bit - not much, but this can lead to a delay in the flow a little longer, which will lead to subsequent sleep.

I know, I know, the time would be insignificant ... but what happens if the system suddenly stops for a few ms ... in this case it will be protected from this.

Update 1

Ok Therefore, I did not understand that you can include TimeSpan as a time value. So I used the code below:

 Thread.Sleep(TimeSpan.FromMilliseconds(1000) - ((DateTime.Now.Subtract(start).TotalMilliseconds >= 1000) ? TimeSpan.FromMilliseconds(0) : DateTime.Now.Subtract(start))); 

If I am right, this should allow me to repeat the stream in exactly 1 second - or as close to the system as possible.

+4
source share
1 answer

IF you set AutoReset = true; , then your theory 1 is correct, otherwise you will have to deal with it in code - see the documentation for Timer on MSDN .

+2
source

Source: https://habr.com/ru/post/1369339/


All Articles