10

I've got a Windows service that needs to do certain things periodically. Should I use waitable timer objects or timer queues?

What are the pros and cons of the two approaches? Is this a false dichotomy? Is there a third way?

Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380

1 Answers1

12

A waitable timer was designed to activate code through an APC. That's pretty hard to get right due to re-entrancy issues and should only be considered if you need to run code on a thread that is otherwise occupied but blocks often enough to allow an APC to run.

Timer queues are very light-weight objects, their callback runs on a (cheap) thread from the thread pool. Almost always good for a periodic service.

A third way is to start a thread when the service is started and have it block with WaitForSingleObject() whose timeout sets the period. You'd wait on an event that signals that the service should stop. Very easy to get going, not as lean as a timer queue.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 2
    Good comments. We tend to pass NULL for the completion routine in SetWaitableTimer, turning it into a normal, waitable, handle. Any pros/cons using it this way vs. timer queues? – Roger Lipscombe Dec 16 '09 at 20:17
  • Another way to do the WaitForSingleObject method would be to use RegisterWaitForSingleObject -- that way you can still use the thread pool. – Aaron Klotz Dec 16 '09 at 21:29
  • Thanks for this - the third idea (wait on an event with WaitForSingleObject() and set the timeout to be the time we need) was a great idea that looks like it will work very well in my particular case. As for the SetWaitableTimer() with no completion routine - this works great as well, at least in my limited experience with it. Not sure about other pros/cons (e.g. which would perform better) but both are good ideas that are easy enough to set up and work well for scenarios where we have a worker thread that needs to execute code on a timed interval without blocking the main thread. – dwillis77 Aug 14 '19 at 06:52