1 // -*- mode: C++; indent-tabs-mode: nil; -*-
4 # include "../config.h"
5 #endif // HAVE_CONFIG_H
13 static timeval normalizeTimeval(const timeval &tm)
17 while (ret.tv_usec < 0) {
20 ret.tv_usec += 1000000;
26 if (ret.tv_usec >= 1000000) {
27 ret.tv_sec += ret.tv_usec / 1000000;
28 ret.tv_usec %= 1000000;
31 if (ret.tv_sec < 0) ret.tv_sec = 0;
37 OBTimer::OBTimer(OBTimerQueueManager *m, OBTimeoutHandler h, OBTimeoutData d)
43 recur = timing = False;
47 OBTimer::~OBTimer(void)
53 void OBTimer::setTimeout(long t)
55 _timeout.tv_sec = t / 1000;
56 _timeout.tv_usec = t % 1000;
57 _timeout.tv_usec *= 1000;
61 void OBTimer::setTimeout(const timeval &t)
63 _timeout.tv_sec = t.tv_sec;
64 _timeout.tv_usec = t.tv_usec;
68 void OBTimer::start(void)
70 gettimeofday(&_start, 0);
74 manager->addTimer(this);
79 void OBTimer::stop(void)
83 manager->removeTimer(this);
87 void OBTimer::halt(void)
93 void OBTimer::fireTimeout(void)
100 timeval OBTimer::timeRemaining(const timeval &tm) const
102 timeval ret = endpoint();
104 ret.tv_sec -= tm.tv_sec;
105 ret.tv_usec -= tm.tv_usec;
107 return normalizeTimeval(ret);
111 timeval OBTimer::endpoint(void) const
115 ret.tv_sec = _start.tv_sec + _timeout.tv_sec;
116 ret.tv_usec = _start.tv_usec + _timeout.tv_usec;
118 return normalizeTimeval(ret);
122 bool OBTimer::shouldFire(const timeval &tm) const
124 timeval end = endpoint();
126 return ! ((tm.tv_sec < end.tv_sec) ||
127 (tm.tv_sec == end.tv_sec && tm.tv_usec < end.tv_usec));
131 void OBTimerQueueManager::fire()
134 timeval now, tm, *timeout = (timeval *) 0;
136 const int xfd = ConnectionNumber(otk::OBDisplay::display);
139 FD_SET(xfd, &rfds); // break on any x events
141 if (! timerList.empty()) {
142 const OBTimer* const timer = timerList.top();
144 gettimeofday(&now, 0);
145 tm = timer->timeRemaining(now);
150 select(xfd + 1, &rfds, 0, 0, timeout);
152 // check for timer timeout
153 gettimeofday(&now, 0);
155 // there is a small chance for deadlock here:
156 // *IF* the timer list keeps getting refreshed *AND* the time between
157 // timer->start() and timer->shouldFire() is within the timer's period
158 // then the timer will keep firing. This should be VERY near impossible.
159 while (! timerList.empty()) {
160 OBTimer *timer = timerList.top();
161 if (! timer->shouldFire(now))
166 timer->fireTimeout();
168 if (timer->isRecurring())
174 void OBTimerQueueManager::addTimer(OBTimer *timer)
177 timerList.push(timer);
180 void OBTimerQueueManager::removeTimer(OBTimer* timer)
183 timerList.release(timer);