CreateWaitableTimer和SetWaitableTimer

负值表示相对时间,正值表示绝对时间,定时器精度为100ns (1ns=1/10亿 s),所以 -50000000 代表5秒,详见MSDN。

程序一为自动重置(先等待5秒,然后每1秒输出一次):

#include "stdafx.h"
#include<Windows.h>
#include<iostream>
#include<time.h>

using namespace std;
int main(){
    LARGE_INTEGER li;   
    li.QuadPart = -50000000;  

     HANDLE hTimer = CreateWaitableTimer( NULL,FALSE,NULL ); 
    if( !SetWaitableTimer( hTimer,&li,1000,NULL,NULL,0 )) {  
        cout<<"error"<<endl;
        CloseHandle( hTimer );   
        return 0;   
    }  
    while ( 1 ){  
        clock_t c_beg = clock();  
        WaitForSingleObject(hTimer,INFINITE);
        clock_t end = clock() - c_beg;  
        cout<<"time:"<<end<<endl;   
    }  
    CloseHandle(hTimer);  
    system("pause");
    return 0;
}

程序二为手动重置(每秒输出),其实当CreateWaitableTimer第二个参数为TRUE时(即手动重置),SetWaitableTimer的第三个参数是不起作用的

#include "stdafx.h"
#include<Windows.h>
#include<iostream>
#include<time.h>

using namespace std;
int main(){
    LARGE_INTEGER li;   
    li.QuadPart = -10000000;  

     HANDLE hTimer = CreateWaitableTimer( NULL,TRUE,NULL ); 
    if( !SetWaitableTimer( hTimer,&li,1000,NULL,NULL,0 )) {  
        cout<<"error"<<endl;
        CloseHandle( hTimer );   
        return 0;   
    }  
    while ( 1 ){  
        clock_t c_beg = clock();  
        WaitForSingleObject(hTimer,INFINITE);
        SetWaitableTimer( hTimer,&li,1000,NULL,NULL,0 );
        clock_t end = clock() - c_beg;  
        cout<<"time:"<<end<<endl;   
    }  
    CloseHandle(hTimer);  
    system("pause");
    return 0;
}

 程序三:APC(异步调用过程)加入定时器

见MSDN http://msdn.microsoft.com/en-us/library/windows/desktop/ms686898%28v=vs.85%29.aspx

原文地址:https://www.cnblogs.com/duyy/p/3755308.html