tags:

views:

103

answers:

1

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?

+1  A: 

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
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
Another way to do the WaitForSingleObject method would be to use RegisterWaitForSingleObject -- that way you can still use the thread pool.
Aaron Klotz