Using Timer Queues Program Example
The following example creates a timer routine that will be executed by a thread from a timer queue after a 10 second delay. First, the code uses the CreateEvent() function to create an event object that is signaled when the timer-queue thread completes. Then it creates a timer queue and a timer-queue timer, using the CreateTimerQueue() and CreateTimerQueueTimer() functions, respectively. The code uses the WaitForSingleObject() function to determine when the timer routine has completed. Finally, the code calls DeleteTimerQueue() to clean up.
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.
Then, add the source file and give it a suitable name.
Next, add the following source code.
void CALLBACK TimerRoutine(PVOID lpParam, BOOLEAN TimerOrWaitFired)
if (lpParam == NULL)
wprintf(LTimerRoutine() lpParam is NULL\n);
// lpParam points to the argument; in this case it is an int
wprintf(LTimer routine called. Parameter is %d.\n, *(int*)lpParam);
HANDLE hTimer = NULL;
HANDLE hTimerQueue = NULL;
int arg = 1234;
// Use an event object to track the TimerRoutine execution
gDoneEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (NULL == gDoneEvent)
wprintf(LCreateEvent() failed, error %d\n, GetLastError());
wprintf(LCreateEvent() is OK!\n);
// Create the timer queue.
hTimerQueue = CreateTimerQueue();
if (NULL == hTimerQueue)
wprintf(LCreateTimerQueue() failed, error %d\n, GetLastError());
wprintf(LCreateTimerQueue() - timer queue was successfully created!\n);
// Set a timer to call the timer routine in 10 seconds.
if (!CreateTimerQueueTimer( &hTimer, hTimerQueue, (WAITORTIMERCALLBACK)TimerRoutine, &arg , 10000, 0, 0))
wprintf(LCreateTimerQueueTimer() failed, error %d\n, GetLastError());
// TODO: Do other useful work here
wprintf(LCreateTimerQueueTimer() - call timer routine in 10 seconds...\n);
// Wait for the timer-queue thread to complete using an event
// object. The thread will signal the event at that time.
if (WaitForSingleObject(gDoneEvent, INFINITE) != WAIT_OBJECT_0)
wprintf(LWaitForSingleObject() failed, error %d\n, GetLastError());
wprintf(LWaitForSingleObject() is OK!\n);
if(CloseHandle(gDoneEvent) != 0)
wprintf(LgDoneEvent handle was closed successfully!\n);
wprintf(LFailed to close gDoneEvent handle, error %d\n, GetLastError());
// Delete all timers in the timer queue.
wprintf(LDeleteTimerQueue() failed, error %d\n, GetLastError());
wprintf(LDeleteTimerQueue() - deleting all timers in the timer queue...\n);
Build and run the project. The following screenshots are sample outputs.