Program 14-3 shows how to use a waitable timer to signal the user periodically.
/* Chapter 14. TimeBeep.c. Periodic alarm. /* Usage: TimeBeep period (in milliseconds). */ #include "EvryThng.h" static BOOL WINAPI Handler (DWORD CntrlEvent); static VOID APIENTRY Beeper (LPVOID, DWORD, DWORD); volatile static BOOL Exit = FALSE; HANDLE hTimer; int _tmain (int argc, LPTSTR argv []) { DWORD Count = 0, Period; LARGE_INTEGER DueTime; /* Catch Ctrl-c to terminate operation. See Chapter 4. */ SetConsoleCtrlHandler (Handler, TRUE); Period = _ttoi (argv [1]) * 1000; DueTime.QuadPart = -(LONGLONG)Period * 10000; /* Due time is negative for first time-out relative to current time. Period is in ms (10^-3 sec) whereas the due time is in 100 ns (10^-7 sec) units to be consistent with a FILETIME. */ hTimer = CreateWaitableTimer (NULL, FALSE /* "Synchronization timer" */, NULL); SetWaitableTimer (hTimer, &DueTime, Period, Beeper, &Count, TRUE); while (!Exit) { _tprintf (_T ("Count = %d\n"), Count); /* Count is increased in the timer routine. */ /* Enter an alertable wait state. */ SleepEx (INFINITE, TRUE); } _tprintf (_T ("Shut down. Count = %d"), Count); CancelWaitableTimer (hTimer); CloseHandle (hTimer); return 0; } static VOID APIENTRY Beeper (LPVOID lpCount, DWORD dwTimerLowValue, DWORD dwTimerHighValue) { *(LPDWORD) lpCount = *(LPDWORD) lpCount + 1; _tprintf (_T ("Perform beep number: %d\n"), *(LPDWORD) lpCount); Beep (1000 /* Frequency. */, 250 /* Duration (ms). */); return; } BOOL WINAPI Handler (DWORD CntrlEvent) { Exit = TRUE; _tprintf (_T ("Shutting Down\n")); return TRUE; }
There are four combinations based on timer type and whether you wait on the handle or use a completion routine.