00001 #ifndef _Q_TIMER_HH_
00002 #define _Q_TIMER_HH_
00003
00004 #include <sys/types.h>
00005 #include <event.h>
00006 #include <iostream>
00007
00008 #include "QTimerDispatcher.hh"
00009
00010 template <class T>
00011 class QTimer
00012 {
00013 public:
00019 typedef void (T::*PtrToMethod)(void);
00020
00022 QTimer();
00023
00028 QTimer(unsigned long timeoutMs);
00029
00031 virtual ~QTimer();
00032
00034 void Start();
00035
00037 void Stop();
00038
00043 void SetTimeout(unsigned long timeoutMs);
00044
00045 void SetSingleShot(bool singleShot) { fSingleShot = singleShot; }
00046
00058 void Connect(PtrToMethod mPtr,T* objPtr);
00059
00060 private:
00062 struct timeval fTimeout;
00063
00065 struct event fEvent;
00066
00068 PtrToMethod fMethPtr;
00069
00071 T* fClassPtr;
00072
00073 bool fSingleShot;
00074
00080 bool fEventIsSet;
00081
00082 void Callback();
00083 static void EventEntryPoint(int fd, short event, void * arg);
00084 };
00085
00086
00087
00088
00089
00090 template <class T>
00091 QTimer<T>::QTimer()
00092 {
00093
00094
00095
00096
00097
00098 QTimerDispatcher::GetInstance();
00099 fSingleShot = false;
00100 fEventIsSet = false;
00101 SetTimeout(0);
00102 }
00103
00104
00105
00106 template <class T>
00107 QTimer<T>::QTimer(unsigned long timeoutMs)
00108 {
00109
00110
00111
00112
00113
00114 QTimerDispatcher::GetInstance();
00115 fSingleShot = false;
00116 fEventIsSet = false;
00117 SetTimeout(timeoutMs);
00118 }
00119
00120
00121
00122 template <class T>
00123 QTimer<T>::~QTimer()
00124 {
00125 Stop();
00126 }
00127
00128
00129
00130 template <class T>
00131 void QTimer<T>::Start()
00132 {
00133 evtimer_set(&fEvent,QTimer::EventEntryPoint,this);
00134 evtimer_add(&fEvent,&fTimeout);
00135 fEventIsSet = true;
00136 QTimerDispatcher::GetInstance().AddTimer();
00137 }
00138
00139
00140
00141 template <class T>
00142 void QTimer<T>::Stop()
00143 {
00144 if(fEventIsSet)
00145 evtimer_del(&fEvent);
00146 }
00147
00148
00149
00150 template <class T>
00151 void QTimer<T>::SetTimeout(unsigned long timeoutMs)
00152 {
00153 fTimeout.tv_sec = timeoutMs / 1000;
00154 fTimeout.tv_usec = (timeoutMs % 1000) * 1000;
00155 }
00156
00157
00158
00159 template <class T>
00160 void QTimer<T>::EventEntryPoint(int fd, short event, void * ptr)
00161 {
00162 QTimer* timer = (QTimer*)ptr;
00163 timer->Callback();
00164 }
00165
00166
00167
00168 template <class T>
00169 void QTimer<T>::Callback()
00170 {
00171 try
00172 {
00173 (fClassPtr->*fMethPtr)();
00174 if(!fSingleShot) evtimer_add(&fEvent,&fTimeout);
00175 }
00176 catch(QError& err)
00177 {
00178 QTimerDispatcher::GetInstance().SetError(err);
00179 }
00180 }
00181
00182
00183
00184 template <class T>
00185 void QTimer<T>::Connect(PtrToMethod mPtr,T* objPtr)
00186 {
00187 fMethPtr = mPtr;
00188 fClassPtr = objPtr;
00189 }
00190
00191 #endif