定时器Timer的实现
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                定时器Timer的实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                
                            
                            
                            定時器Timer的實現
   
  
  
  
 
  
 
  
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
                        
                        
                        ??????? 定時器在實際項目中會用的比較平凡。因此,本文首先介紹定時器Timer的windows版本,跨平臺的定時器將在下一篇文章中介紹。它們的源代碼均用C++編寫。源代碼詳見:https://github.com/duankai/Timer。
1.??????定時器結構體類型
typedef struct TIMER_T {int uiTimerID;long lMilliSecond;void (* lpProcessFunction)(void * pvData);void * pvData; } TIMER_T;2.??????定時器類
class Timer { public:Timer();int SetTimer(long lMilliSecond, //the millisecond of timervoid (*_lpProcessFunction)(void * pvData),void * pvData);bool CancleTimer(int ulTimerID);bool GetInstanceStatus();~Timer(); private:static DWORD WINAPI ScanTimerQueue(LPVOID lp);static int CmpFunc(TIMER_T * t1, TIMER_T * t2); private:static SortBinaryTree<TIMER_T> * m_pstSBT;static int m_uiTimerID;bool m_bInit;HANDLE m_hScan;std::map<int, TIMER_T *> m_map; };3.??????定時器的設置
int Timer::SetTimer(long lMilliSecond, //the millisecond of timervoid (*_lpProcessFunction)(void * pvData),void * pvData ) {TIMER_T * stTimerInstc = (TIMER_T *)malloc(sizeof(TIMER_T));if (!stTimerInstc){return INVILID_TIMER_ID;}stTimerInstc->lpProcessFunction = _lpProcessFunction;/*The GetTickCount() function will be zero when your system run more than 49.7 days.*/stTimerInstc->lMilliSecond = GetTickCount() + lMilliSecond;stTimerInstc->uiTimerID = ++m_uiTimerID;stTimerInstc->pvData = pvData;if (m_pstSBT->InsertTreeNode(stTimerInstc)){m_map.insert(std::pair<int,TIMER_T *>(m_uiTimerID, stTimerInstc));return m_uiTimerID;} else{free(stTimerInstc);stTimerInstc = NULL;return INVILID_TIMER_ID; } }4.??????取消定時器
bool Timer::CancleTimer(int ulTimerID) {std::map<int, TIMER_T *>::iterator itor_map;itor_map = m_map.find(ulTimerID);if (itor_map == m_map.end()){return false;}if (m_pstSBT->DeleteTreeNode((void *)itor_map->second)){free(itor_map->second);itor_map->second = NULL;m_map.erase(itor_map);return true;}else{return false; } }
5.??????定時器掃描隊列
DWORD WINAPI Timer::ScanTimerQueue(LPVOID lp) {LONG ulCurrTime;while(1){ulCurrTime = GetTickCount();if (NULL != m_pstSBT->GetSmallestNode() &&m_pstSBT->GetSmallestNode()->lMilliSecond <= ulCurrTime){TIMER_T * pstTimer = m_pstSBT->DeleteSmallestNode();if (NULL != pstTimer){pstTimer->lpProcessFunction(pstTimer->pvData);free(pstTimer);pstTimer = NULL;}}SLEEP(100);}return 0; }
??????? 總結:Timer實現了定時器的主要功能,設置定時器和取消定時器,同時,在設置定時器時通過提供一個回調函數來完成相關工作。定時器存儲在SortBinaryTree中,便于掃描。
??????? 存在的問題:由于在設置定時器的時候采用了GetTickCount()函數,因此限制了服務器的連續運行時間不得超過49.7天,在大型服務代碼的編寫中,這將通過其他替代函數完成這一類似功能。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的定时器Timer的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: zImage与uImage的区别
- 下一篇: 如何修改linux的MAC地址
