#ifndef TIMER__H_ #define TIMER__H_ #ifdef _WIN32 #pragma once #endif #include #define HTIMER_INTERVAL_TIME 100 // 100 ms #define HTIMER_TERMINATE_WAIT_TIME 300 // 300 ms #define HTIMER() (&g_timerGlobal) #define ON_TIMER(CLASS_NAME, FN_CALLBACK) \ inline bool SetTimer(unsigned int nTimerID, unsigned int nElapse) { return HTIMER()->SetTimer(nTimerID, nElapse, TimerCallBack##FN_CALLBACK, this); } \ inline bool KillTimer(unsigned int nTimerID) { return HTIMER()->KillTimer(nTimerID); } \ static void TimerCallBack##FN_CALLBACK(unsigned int nTimerID, void * pParam) { static_cast(pParam)->FN_CALLBACK(nTimerID); } \ void FN_CALLBACK(unsigned int nTimerID); struct HTimerObject { unsigned int nTimerID; unsigned int nElapse; unsigned int dwLastCheckTime; bool bDelete; void (*fnOnTimerCallBack)(unsigned int, void *); void * pOnTimerCallBackParam; }; typedef std::list LIST_TIMER_OBJECT; class HTimer : public HThread { public: HTimer(); ~HTimer(); inline void Terminate() { m_bTerminate = true; Sleep(HTIMER_TERMINATE_WAIT_TIME); } void GetSystemTime(PSYSTEMTIME pSystemTime); inline unsigned int GetTickCount() { return m_nTickCount; } LIST_TIMER_OBJECT * GetTimerList() { return &m_listTimer; } bool SetTimer(unsigned int nTimerID, unsigned int nElapse, void (*fnCallBack)(unsigned int, void *), void * pParam); bool KillTimer(unsigned int nTimerID); void RemoveAllTimer(); protected: void Main(); private: volatile bool m_bThreadStarted; volatile bool m_bTerminate; #ifndef SINGLE_THREADED_MODEL HSyncObject m_sync; HSyncObject m_syncSystemTime; #endif volatile SYSTEMTIME m_systemTime; volatile DWORD m_nTickCount; LIST_TIMER_OBJECT m_listTimer; }; extern HTimer g_timerGlobal; #endif // TIMER__H_