// Sample for Waitable Timers under Windows 32 Bit // Works! // s. J.Richter: Advanced Windows (3rd ed.), S.440ff // Dr.E.Huckert 03-2007 // Testet with Digital Mars C++ Compiler // Compile as follows: dmc -mn WaitableTimer.cpp // must be defined - if not some declarations are not recognized in windows.h #define _WIN32_WINNT 0x0500 #include #include static HANDLE hTimer = 0; // global timer object static long argument = 17L; static unsigned count = 0; static DWORD lastLow = 0L; static DWORD lastHigh = 0L; // callback function VOID CALLBACK MyTimerCallback(LPVOID pArg, DWORD timeLowValue, DWORD timeHighValue) { count++; // be careful not to use printf() if we are in a thread routine! printf( "In Callback Routine count=%u argument=%ld timeHigh=%lu timeLow=%lu\n", count, *(long *)pArg, (unsigned long)timeHighValue, (unsigned long)timeLowValue); fflush(stdout); if (lastLow != 0L) printf("Diff. Time=%lu\n", (unsigned long)(timeLowValue - lastLow)); // note: the timer difference does not correspond to the interval value! // Is this due to the 50/60 Hz difference between US/Europe? // The ratios for different intervals are correct however! lastLow = timeLowValue; lastHigh = timeHighValue; } int main(int argc, char *argv[]) { // create a timer HANDLE hTimer = CreateWaitableTimer(NULL, FALSE, "MyWaitableTimer"); if (hTimer != 0) { printf("waitable timer created\n"); // // Define the start time: 200 ms from now on (negative value = relative time) // Note: if abs. time: absolute time values must be in UTC LARGE_INTEGER startTime; startTime.QuadPart = -200000L; // start in 200ms from now on // // Declare the callback function with an argument address to be transferred int ret = SetWaitableTimer(hTimer, &startTime, 100L, // interval 100 ms MyTimerCallback, &argument, FALSE); if (ret == 0) { DWORD errcode = GetLastError(); printf("ERROR: SetWaitableTimer fails. code=%lu\n", errcode); exit(1); } // // wait for a signal with 20 secs timeout printf("waiting for a signal from the callback routine\n"); // Note: The code using WaitForSingleObject() does not work! // Note: Use SleepEx() instead! //~ ret = WaitForSingleObject(hTimer, 20000L); //~ if (ret == WAIT_TIMEOUT) //~ printf("timeout signaled\n"); //~ else //~ printf("received signal from timer callback routine\n"); while (count < 20) { SleepEx(20000L, TRUE); // Don not use Sleep() - always SleepEx()!!!!! argument++; } // // stop the timer CancelWaitableTimer(hTimer); printf("timer canceled with timer count=%u\n", count); } else printf("ERROR: could not create the timer\n"); return 0; }