00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039 #include "Timer.h"
00040
00041 namespace ariba {
00042 namespace utility {
00043
00044 use_logging_cpp(Timer);
00045 SystemEventType TimerEventType("Timer");
00046
00047 Timer::Timer() {
00048 running = false;
00049
00050 #ifndef UNDERLAY_OMNET
00051 timerThread = NULL;
00052 #endif // UNDERLAY_OMNET
00053 }
00054
00055 Timer::~Timer() {
00056 #ifndef UNDERLAY_OMNET
00057 if( running ){
00058 running = false;
00059
00060 timerThread->join();
00061 delete timerThread;
00062 timerThread = NULL;
00063 }
00064 #endif // UNDERLAY_OMNET
00065 }
00066
00067 void Timer::setInterval(unsigned int millis, bool oneshot) {
00068 this->millis = millis;
00069 this->oneshot = oneshot;
00070 }
00071
00072 void Timer::start() {
00073 if( running ) return;
00074
00075 #ifndef UNDERLAY_OMNET
00076
00077 if( timerThread == NULL )
00078 timerThread = new boost::thread(boost::bind(&Timer::threadFunc, this) );
00079 #else
00080 running = true;
00081 SystemQueue::instance().scheduleEvent(
00082 SystemEvent( this, TimerEventType, NULL), millis );
00083 #endif
00084 }
00085
00086 void Timer::reset(){
00087 #ifndef UNDERLAY_OMNET
00088 if(timerThread == NULL) return;
00089 timerThread->interrupt();
00090 #else
00091 #error timer interruption not implemented for omnet
00092 #endif
00093 }
00094
00095 bool Timer::isRunning(){
00096 return running;
00097 }
00098
00099 void Timer::stop() {
00100 running = false;
00101 reset();
00102 }
00103
00104 void Timer::eventFunction() {
00105
00106 }
00107
00108 #ifndef UNDERLAY_OMNET
00109 void Timer::threadFunc( Timer* obj ) {
00110 obj->running = true;
00111
00112 while( obj->running ) {
00113
00114 try{
00115
00116 boost::this_thread::sleep( boost::posix_time::milliseconds(obj->millis) );
00117 if (obj->running)
00118 SystemQueue::instance().scheduleEvent( SystemEvent( obj, TimerEventType, NULL), 0 );
00119
00120 }catch(boost::thread_interrupted e){
00121
00122
00123 }
00124
00125 if( obj->oneshot ) break;
00126 }
00127
00128 if(! obj->oneshot )
00129 obj->running = false;
00130 }
00131 #endif // UNDERLAY_OMNET
00132
00133 void Timer::handleSystemEvent( const SystemEvent& event ) {
00134 if( running ){
00135 if( oneshot ) running = false;
00136 eventFunction();
00137 }
00138
00139 #ifdef UNDERLAY_OMNET
00140 if( ! oneshot && running )
00141 SystemQueue::instance().scheduleEvent(
00142 SystemEvent( this, TimerEventType, NULL), millis );
00143 #endif
00144 }
00145
00146 }}