I think it really depends on your requirement.
case 1. Suppose you want to run this.ExecuteTask() every five minutes starting at 12:00 (ie 12:00, 12:05, ...), and suppose that this.ExecuteTask() changes (e.g. from 30 seconds to 2 minutes), perhaps using a timer instead of Thread.Sleep () seems to be an easier way to do this (at least for me).
However, you can achieve this behavior with Thread.Sleep() , as well as by calculating the offset, taking timestamps when the thread wakes up and this.ExecuteTask() .
Case 2. Suppose you want to complete a task in the next 5 minutes immediately after completing this.ExecuteTask() , using Thread.Sleep() seems simpler. Again, you can achieve this behavior with a timer, as well as by reprogramming the timer each time the offsets are calculated each time this.ExecuteTask() completes.
Note1 , for case 1, you have to be very careful in the following scenario: what if this.ExecuteTask() sometimes takes longer than the period (i.e. starts at 12:05 and ends at this.ExecuteTask() in the example above).
What does this mean for your application and how will it be processed?
a. A general failure is to abort the service or interrupt the execution of the current (12:05) at 12:10 and start the execution at 12:10.
b. Not a big deal (skip 12:10 and run this.ExecuteTask() at 12:15).
with. It doesn’t matter, but you need to start 12:10 execution immediately after the completion of task 12:05 (what if it holds for more than 5 minutes?).
e. It is necessary to start execution 12:10, although execution 12:05 is executed.
e. anything else?
For the policy that you selected above, does your choice of implementation (timer or Thread.Sleep() ) allow you to support your policy?
Note 2 . There are several timers that you can use in .NET. Please see the following document (even if it's a bit outdated, but it seems to be a good start): Comparing timer classes in the .NET Framework class library
source share