00001
00002 #ifndef __timer_hh
00003 #define __timer_hh
00004
00005
00006
00007
00008
00009 extern "C" {
00010 #ifdef TIME_WITH_SYS_TIME
00011 # include <sys/time.h>
00012 # include <time.h>
00013 #else // !TIME_WITH_SYS_TIME
00014 # ifdef HAVE_SYS_TIME_H
00015 # include <sys/time.h>
00016 # else // !HAVE_SYS_TIME_H
00017 # include <time.h>
00018 # endif // HAVE_SYS_TIME_H
00019 #endif // TIME_WITH_SYS_TIME
00020 }
00021
00022 #include <queue>
00023 #include <vector>
00024
00025 namespace otk {
00026
00027
00028
00029
00030
00031
00032 class Timer {
00033 public:
00034
00035 typedef void (*TimeoutHandler)(void *data);
00036
00037 private:
00038
00039 struct TimerCompare {
00040
00041 inline bool operator()(const Timer *a, const Timer *b) const {
00042 return timercmp(&a->_timeout, &b->_timeout, >);
00043 }
00044 };
00045 friend struct TimerCompare;
00046
00047 typedef
00048 std::priority_queue<Timer*, std::vector<Timer*>, TimerCompare> TimerQ;
00049
00050
00051 long _delay;
00052
00053 TimeoutHandler _action;
00054
00055 void *_data;
00056
00057 bool _del_me;
00058
00059 struct timeval _last;
00060
00061 struct timeval _timeout;
00062
00063
00064 static TimerQ _q;
00065
00066 static timeval _nearest_timeout;
00067
00068 static timeval _now;
00069
00070
00071
00072
00073
00074 static void realDelete(Timer *self);
00075
00076
00077
00078
00079
00080
00081 static void timevalAdd(timeval &a, long msec);
00082
00083 public:
00084
00085
00086
00087
00088
00089
00090 Timer(long delay, TimeoutHandler cb, void *data);
00091
00092
00093
00094
00095
00096 void operator delete(void *self);
00097
00098
00099
00100
00101
00102 static void dispatchTimers(bool wait = true);
00103
00104
00105
00106
00107
00108
00109
00110 static bool nearestTimeout(struct timeval &tm);
00111
00112
00113 static void initialize(void);
00114
00115
00116 static void destroy(void);
00117 };
00118
00119 }
00120
00121 #endif // __timer.hh