1: #include "StdAfx.h"
2: #include "TimerMgr.h"
3:
4:
5: CTimerMgr::CTimerMgr(void):m_hTimerQueue(NULL)
6: {
7: m_hTimerQueue = ::CreateTimerQueue();
8: VERIFY(NULL != m_hTimerQueue);
9: }
10:
11:
12: CTimerMgr::~CTimerMgr(void)
13: {
14: if (NULL != m_hTimerQueue)
15: {
16: // INVALID_HANDLE_VALUE:会导致DeleteTimerQueueEx等待所有的timer对应的回调方法完成后再返回
17: DeleteTimerQueueEx(m_hTimerQueue,NULL);
18: }
19: }
20:
21: // dwElapse :milliseconds
22: bool CTimerMgr::SetTimer( DWORD dwID,DWORD dwElapse,TimerFunObj timerfunc,DWORD dwUserData)
23: {
24: VERIFY(NULL != m_hTimerQueue);
25:
26: TCBParam* ptParam = new TCBParam;
27: ptParam->m_pThis = this;
28: ptParam->m_dwTimerID = dwID;
29: ptParam->m_func = timerfunc;
30: ptParam->m_dwUserData = dwUserData;
31:
32: HANDLE hTimer = NULL;
33: if( 0 != CreateTimerQueueTimer(&hTimer,m_hTimerQueue,(WAITORTIMERCALLBACK)TimerCBProc,(void*)ptParam,dwElapse,0,WT_EXECUTEDEFAULT))
34: {
35: m_mapTimerID2Handle[dwID] = hTimer;
36: return true;
37: }
38: else //失败
39: {
40: delete ptParam;
41: ptParam = NULL;
42: return false;
43: }
44:
45: }
46:
47: bool CTimerMgr::KillTimer( DWORD dwID )
48: {
49: MAP_ID_2_HANDLE::iterator it = m_mapTimerID2Handle.find(dwID);
50:
51: if (it == m_mapTimerID2Handle.end())//不存在
52: return false;
53:
54: HANDLE hTimer = it->second;
55: BOOL bSuc = ( 0 != ::DeleteTimerQueueTimer(m_hTimerQueue,hTimer,NULL) );
56:
57: if (bSuc )
58: {
59: m_mapTimerID2Handle.erase(it);
60: return true;
61: }
62: //之前定义的处理函数即将被调用或正在被调用,立刻返回,但系统会在处理函数调用完成后自动删除这个定时器
63: else if (ERROR_IO_PENDING == GetLastError())
64: {
65: m_mapTimerID2Handle.erase(it);
66: return true;
67: }
68: else
69: {
70: return false;
71: }
72:
73:
74:
75:
76: }
77:
78:
79: void _stdcall TimerCBProc( PVOID lpParamter,BOOL TimerorWaitFired )
80: {
81: TCBParam* ptParam = (TCBParam*)lpParamter;
82: if (NULL == ptParam)
83: return;
84: CTimerMgr* pThis = ptParam->m_pThis;
85: DWORD dwTimerID = ptParam->m_dwTimerID;
86: TimerFunObj funcTimer = ptParam->m_func;
87: DWORD dwUserData = ptParam->m_dwUserData;
88:
89: funcTimer(dwTimerID,dwUserData);
90:
91: delete ptParam;
92: ptParam = NULL;
93: }