Chapter09“内核模式下的线程同步”之可等待的计时器内核对象

可等待的计时器是在某个时间点或一个时间周期内自动触发它们本身的内核对象。与之对应的几个函数:

1)       创建可等待计时器函数——CreateWaitableTimer函数
HANDLE WINAPI CreateWaitableTimer(
                                   __in_optLPSECURITY_ATTRIBUTES lpTimerAttributes,
                                     __inBOOL bManualReset,
                                   __in_optLPCTSTR lpTimerName );
第一个参数指定安全属性,
第二个参数如果是TRUE,则表示是手动设置通知的计时器;如果是FALSE,则表示是异步计时器。
第三个参数指定计时器名。


2)       打开一个已经创建的可等待计时器函数——OpenWaitableTimer函数
HANDLE WINAPI OpenWaitableTimer(
                                                               __inDWORD dwDesiredAccess,
                                                               __inBOOL bInheritHandle,
                                                               __inLPCTSTR lpTimerName );
第一个参数指定想要的访问权限。
第二个参数指定是否是继承句柄。
第三个参数标记计时器名。


3)       由于每个内核对象计数器初始化时都是被设置为非触发状态,所有要想让计时器转为触发状态,需要用到另一个函数——SetWaitableTimer函数
BOOL WINAPI SetWaitableTimer(
                                                        __inHANDLE hTimer,
                                                        __inconst LARGE_INTEGER *pDueTime,
                                                        __inLONG lPeriod,
                                                        __in_optPTIMERAPCROUTINE pfnCompletionRoutine,
                                                        __in_optLPVOID lpArgToCompletionRoutine,
                                                        __inBOOL fResume)
具体参数请查看上面函数名的MSDN链接。


4)       取消计时器——CancelWaitableTimer函数
BOOL CancelWaitableTimer(HANDLE hTimer);
其参数就是创建计时器时返回的句柄。

 

 

一个示例:

// Declare our local variables.
HANDLE hTimer;
SYSTEMTIME st;
FILETIME ftLocal, ftUTC;
LARGE_INTEGER liUTC;
// Create an auto-reset timer.
hTimer = CreateWaitableTimer(NULL, FALSE, NULL);
// First signaling is at January 1, 2008, at 1:00 P.M. (local time).
st.wYear = 2008; // Year
st.wMonth = 1; // January
st.wDayOfWeek = 0; // Ignored
st.wDay = 1; // The first of the month
st.wHour = 13; // 1PM
st.wMinute = 0; // 0 minutes into the hour
st.wSecond = 0; // 0 seconds into the minute
st.wMilliseconds = 0; // 0 milliseconds into the second
SystemTimeToFileTime(&st, &ftLocal);
// Convert local time to UTC time.
LocalFileTimeToFileTime(&ftLocal, &ftUTC);
// Convert FILETIME to LARGE_INTEGER because of different alignment.
liUTC.LowPart = ftUTC.dwLowDateTime;
liUTC.HighPart = ftUTC.dwHighDateTime;
// Set the timer.
SetWaitableTimer(hTimer, &liUTC, 6 * 60 * 60 * 1000,
NULL, NULL, FALSE); ...


原文地址:https://www.cnblogs.com/java20130722/p/3207134.html