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(L"TimerRoutine() lpParam is NULL\n");
// lpParam points to the argument; in this case it is an int
wprintf(L"Timer 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(L"CreateEvent() failed, error %d\n", GetLastError());
wprintf(L"CreateEvent() is OK!\n");
// Create the timer queue.
hTimerQueue = CreateTimerQueue();
if (NULL == hTimerQueue)
wprintf(L"CreateTimerQueue() failed, error %d\n", GetLastError());
wprintf(L"CreateTimerQueue() - 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(L"CreateTimerQueueTimer() failed, error %d\n", GetLastError());
// TODO: Do other useful work here
wprintf(L"CreateTimerQueueTimer() - 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(L"WaitForSingleObject() failed, error %d\n", GetLastError());
wprintf(L"WaitForSingleObject() is OK!\n");
if(CloseHandle(gDoneEvent) != 0)
wprintf(L"gDoneEvent handle was closed successfully!\n");
wprintf(L"Failed to close gDoneEvent handle, error %d\n", GetLastError());
// Delete all timers in the timer queue.
wprintf(L"DeleteTimerQueue() failed, error %d\n", GetLastError());
wprintf(L"DeleteTimerQueue() - deleting all timers in the timer queue...\n");
Build and run the project. The following screenshots are sample outputs.