#define _SECOND 10000000
//回调函数
VOID CALLBACK TimerAPCProc(LPVOID lpArg,DWORD dwTimerLowValue,DWORD dwTimerHighValue )
{
printf("Timer was signaled.\n");
}
int _tmain(int argc, _TCHAR* argv[]){ LARGE_INTEGER liDueTime; //创建WaitableTimer HANDLE hTimer = CreateWaitableTimer(NULL, TRUE, NULL); if(hTimer) { //2秒后启用 liDueTime.QuadPart = -2 * _SECOND; //设置计时器属性 int result = SetWaitableTimer(hTimer,&liDueTime,1000,TimerAPCProc,NULL,FALSE); if(0< result) { printf("Waiting for 2 seconds...\n"); while(true) //如果此处不循环调用Ex函数,是不执行回调函数的 { /*SleepEx(INFINITE, TRUE);*/ WaitForSingleObjectEx(hTimer, INFINITE,TRUE); //调用SleepEx和WaitForSingleObjectEx效果等效 } } } return 0;}
查MSDN,才搞明白:
线程必须是由于调用 SleepEX,WaitForSingleObjectEx,WaitForMultipleObjectsEX,MSGWaitForMultipleObjectsEx 或 SignalObjectAndWait而进入等待的状态。否则,系统不会把计时器的APC函数添加到队列中。
This thread must be in an alertable state to execute the completion routine. It accomplishes this by calling the SleepEx function, which is an alertable function.