00001
00002 #ifndef TIMER_H
00003 #define TIMER_H
00004
00005 #include <iostream>
00006 using namespace std;
00007 #include <boost/shared_ptr.hpp>
00008 #include <boost/utility.hpp>
00009
00010 #include "node.hpp"
00011 #include "event.hpp"
00012 #include "sim_time.hpp"
00013
00019 class Timer : boost::noncopyable {
00020 public:
00022 typedef boost::shared_ptr<Timer> TimerPtr;
00023
00031 static inline TimerPtr create(NodePtr owner, EventPtr eventOnFire);
00032
00048 inline bool start(const SimTime& delay) const;
00049
00059 inline bool stop() const;
00060
00073 inline bool reschedule(const SimTime& delay) const;
00074
00084 inline bool isRunning() const;
00085
00095 inline SimTime timeRemaining() const;
00096
00109 void setEvent(const EventPtr eventOnFire);
00110
00111 protected:
00112
00117 Timer(NodePtr owner, EventPtr eventOnFire);
00118
00119 private:
00120
00122 NodePtr m_owner;
00123
00126 EventPtr m_eventOnFire;
00127
00128 };
00129 typedef boost::shared_ptr<Timer> TimerPtr;
00130
00132
00134
00135 inline TimerPtr Timer::create(NodePtr owner, EventPtr eventOnFire)
00136 {
00137 TimerPtr p(new Timer(owner, eventOnFire));
00138 return p;
00139 }
00140
00141 inline bool Timer::start(const SimTime& delay) const
00142 {
00143 assert(m_owner != 0);
00144 assert(m_eventOnFire != 0);
00145
00146 bool didScheduleEvent = false;
00147 if(!isRunning()) {
00148 didScheduleEvent = m_owner->scheduleEvent(m_eventOnFire, delay);
00149 }
00150 return didScheduleEvent;
00151 }
00152
00153 inline bool Timer::stop() const
00154 {
00155 assert(m_owner != 0);
00156 assert(m_eventOnFire != 0);
00157
00158 bool didCancelEvent = false;
00159 if(isRunning()) {
00160 didCancelEvent = m_owner->cancelEvent(m_eventOnFire);
00161 }
00162 return didCancelEvent;
00163 }
00164
00165 inline bool Timer::reschedule(const SimTime& delay) const
00166 {
00167 bool wasSuccessful = true;
00168 if(isRunning()) {
00169 wasSuccessful &= stop();
00170 }
00171 wasSuccessful &= start(delay);
00172
00173 return wasSuccessful;
00174
00175 }
00176
00177 inline bool Timer::isRunning() const
00178 {
00179 assert(m_eventOnFire != 0);
00180 return m_eventOnFire->inEventQueue();
00181 }
00182
00183 inline SimTime Timer::timeRemaining() const
00184 {
00185 assert(m_owner != 0);
00186 assert(m_eventOnFire != 0);
00187
00188 SimTime timeLeft(0.0);
00189 if(isRunning()) {
00190 timeLeft = m_eventOnFire->getFireTime() - m_owner->currentTime();
00191 assert(timeLeft.isValid());
00192 }
00193
00194 return timeLeft;
00195 }
00196
00198
00200
00201 inline ostream& operator<< (ostream& s, const Timer& timer)
00202 {
00203 return s<< "Timer state (pointer=" << &timer << ") isRunning=" <<
00204 timer.isRunning() << " timeRemaining=" << timer.timeRemaining();
00205 }
00206
00207 #endif // TIMER_H
00208