#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
VOID CALLBACK TimerRoutine(PVOID lpParam, BOOLEAN TimerOrWaitFired)
{
printf("World!\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hTimer = NULL;
HANDLE hTimerQueue = NULL;
int arg = 123;
// Create the timer queue.
hTimerQueue = CreateTimerQueue();
if (NULL == hTimerQueue)
{
printf("CreateTimerQueue failed (%d)\n", GetLastError());
return 2;
}
// Set a timer to call the timer routine in 1 seconds.
if (!CreateTimerQueueTimer( &hTimer, hTimerQueue,
(WAITORTIMERCALLBACK)TimerRoutine, &arg , 200, 1000, WT_EXECUTEDEFAULT))
{
printf("CreateTimerQueueTimer failed (%d)\n", GetLastError());
return 3;
}
while(1)
{
printf("Hello!\n");
Sleep(1000);
}
DeleteTimerQueueTimer(hTimerQueue,hTimer,NULL);
// Delete all timers in the timer queue.
if (!DeleteTimerQueue(hTimerQueue))
printf("DeleteTimerQueue failed (%d)\n", GetLastError());
return 0;
}
使用内核定时器多好,连消息循环都不用建的。
供参考:
C/C++ code
// 析构函数
CTimer::~CTimer()
{
ITER iter = m_hTimerMap.begin();
ITER enditer = m_hTimerMap.end();
for (; iter != enditer; ++iter)
{
DeleteTimerQueueTimer(m_hTimerQueue, iter->second, INVALID_HANDLE_VALUE);
}
DeleteTimerQueueEx(m_hTimerQueue, INVALID_HANDLE_VALUE);
}
// 创建定时器
BOOL CTimer::Create(PVOID pvCallBack, PVOID pvParam, DWORD dwDueTime, DWORD dwPeriod, ULONG dwFlags)
{
if (IsExist(pvCallBack)) return FALSE;
// 创建定时器队列
if (m_hTimerQueue == NULL)
{
m_hTimerQueue = CreateTimerQueue();
}
// 创建并保存
HANDLE hTimer = NULL;
BOOL bRet = CreateTimerQueueTimer(
&hTimer,
m_hTimerQueue,
(WAITORTIMERCALLBACK)pvCallBack,
pvParam,
dwDueTime,
dwPeriod,
dwFlags);
if (bRet)
{
m_hTimerMap.insert(TYPE(pvCallBack, hTimer));
}
return bRet;
}
// 修改定时器
BOOL CTimer::Change(PVOID pvCallBack, DWORD dwDueTime, DWORD dwPeriod)
{
ITER iter = m_hTimerMap.find(pvCallBack);
if (iter != m_hTimerMap.end() &&
ChangeTimerQueueTimer(m_hTimerQueue, iter->second, dwDueTime, dwPeriod))
{
return TRUE;
}
return FALSE;
}
// 删除定时器
BOOL CTimer::Delete(PVOID pvCallBack, HANDLE hCompletionEvent)
{
ITER iter = m_hTimerMap.find(pvCallBack);
if (iter != m_hTimerMap.end() &&
DeleteTimerQueueTimer(m_hTimerQueue, iter->second, hCompletionEvent))
{
m_hTimerMap.erase(pvCallBack);
return TRUE;
}
return FALSE;
}
// 清除所有定时器
BOOL CTimer::Clear()
{
if (m_hTimerMap.size() == 0) return FALSE;
for (ITER iter = m_hTimerMap.begin(); iter != m_hTimerMap.end(); ++iter)
{
DeleteTimerQueueTimer(m_hTimerQueue, iter->second, INVALID_HANDLE_VALUE);
}
m_hTimerMap.clear();
return TRUE;
}
// 定时器是否存在
BOOL CTimer::IsExist(PVOID pvCallBack)
{
ITER iter = m_hTimerMap.find(pvCallBack);
if (iter != m_hTimerMap.end())
{
return TRUE;
}
else
{
return FALSE;
}
}