Synchronizing a timer to prevent overlap

后端 未结 6 2206
谎友^
谎友^ 2020-12-08 21:02

I\'m writing a Windows service that runs a variable length activity at intervals (a database scan and update). I need this task to run frequently, but the code to handle isn

6条回答
  •  旧巷少年郎
    2020-12-08 21:35

    You could do it with a Timer, but you would need to have some form of locking on your database scan and update. A simple lock to synchronize may be enough to prevent multiple runs from occurring.

    That being said, it might be better to start a timer AFTER you're operation is complete, and just use it one time, then stop it. Restart it after your next operation. This would give you 30 seconds (or N seconds) between events, with no chance of overlaps, and no locking.

    Example :

    System.Threading.Timer timer = null;
    
    timer = new System.Threading.Timer((g) =>
      {
          Console.WriteLine(1); //do whatever
    
          timer.Change(5000, Timeout.Infinite);
      }, null, 0, Timeout.Infinite);
    

    Work immediately .....Finish...wait 5 sec....Work immediately .....Finish...wait 5 sec....

提交回复
热议问题