| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134 |
- #pragma once
- #include <atlbase.h>
- static void CALLBACK TimerProc(void*, BOOLEAN);
- ///////////////////////////////////////////////////////////////////////////////
- //
- // class CTimer
- //
- class CTimer
- {
- public:
- CTimer()
- {
- m_hTimer = NULL;
- m_mutexCount = 0;
- m_bTimerStart = false;
- }
- virtual ~CTimer()
- {
- Stop();
- }
- bool Start(unsigned int interval, // interval in ms
- bool immediately = false,// true to call first event immediately
- bool once = false, // true to call timed event only once
- ULONG Flags = WT_EXECUTEINTIMERTHREAD)
- {
- if( m_hTimer )
- {
- return false;
- }
- SetCount(0);
- BOOL success = CreateTimerQueueTimer( &m_hTimer,
- NULL,
- TimerProc,
- this,
- immediately ? 0 : interval,
- once ? 0 : interval,
- Flags);
- if (success != 0)
- {
- m_bTimerStart = true;
- }
- return (success != 0);
- }
- void Stop()
- {
- m_bTimerStart = false;
- DeleteTimerQueueTimer( NULL, m_hTimer, NULL );
- m_hTimer = NULL ;
- }
- void StopSafely()
- {
- m_bTimerStart = false;
- DeleteTimerQueueTimer( NULL, m_hTimer, INVALID_HANDLE_VALUE );
- m_hTimer = NULL ;
- }
- virtual void OnTimedEvent()
- {
- // Override in derived class
- }
- void SetCount(int value)
- {
- InterlockedExchange( &m_mutexCount, value );
- }
- int GetCount()
- {
- return InterlockedExchangeAdd( &m_mutexCount, 0 );
- }
- bool IsTimerStart(){return m_bTimerStart;}
- private:
- HANDLE m_hTimer;
- long m_mutexCount;
- bool m_bTimerStart;
- };
- ///////////////////////////////////////////////////////////////////////////////
- //
- // TimerProc
- //
- void CALLBACK TimerProc(void* param, BOOLEAN timerCalled)
- {
- CTimer* timer = static_cast<CTimer*>(param);
- timer->SetCount( timer->GetCount()+1 );
- timer->OnTimedEvent();
- };
- ///////////////////////////////////////////////////////////////////////////////
- //
- // template class TTimer
- //
- template <class T> class TTimer : public CTimer
- {
- public:
- typedef private void (T::*TimedFunction)(void);
- TTimer()
- {
- m_pTimedFunction = NULL;
- m_pClass = NULL;
- }
- void SetTimedEvent(T *pClass, TimedFunction pFunc)
- {
- m_pClass = pClass;
- m_pTimedFunction = pFunc;
- }
- protected:
- void OnTimedEvent()
- {
- if (m_pTimedFunction && m_pClass)
- {
- (m_pClass->*m_pTimedFunction)();
- }
- }
- private:
- T *m_pClass;
- TimedFunction m_pTimedFunction;
- };
|