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 stop();
00058 if(timerThread != NULL){
00059 delete timerThread;
00060 timerThread = NULL;
00061 }
00062 #endif // UNDERLAY_OMNET
00063 }
00064
00065 void Timer::setInterval(unsigned int millis, bool oneshot) {
00066 this->millis = millis;
00067 this->oneshot = oneshot;
00068 }
00069
00070 void Timer::start() {
00071 if( running ) return;
00072
00073 #ifndef UNDERLAY_OMNET
00074
00075 if( timerThread == NULL )
00076 timerThread = new boost::thread(boost::bind(&Timer::threadFunc, this) );
00077 #else
00078 running = true;
00079 SystemQueue::instance().scheduleEvent(
00080 SystemEvent( this, TimerEventType, NULL), millis );
00081 #endif
00082 }
00083
00084 void Timer::reset(){
00085 #ifndef UNDERLAY_OMNET
00086 if(timerThread == NULL) return;
00087 timerThread->interrupt();
00088 #else
00089 #error timer interruption not implemented for omnet
00090 #endif
00091 }
00092
00093 bool Timer::isRunning(){
00094 return running;
00095 }
00096
00097 void Timer::stop() {
00098 running = false;
00099 reset();
00100 SystemQueue::instance().dropAll(this);
00101 if(timerThread != NULL)
00102 timerThread->join();
00103 }
00104
00105 void Timer::eventFunction() {
00106
00107 }
00108
00109 #ifndef UNDERLAY_OMNET
00110 void Timer::threadFunc( Timer* obj ) {
00111 obj->running = true;
00112
00113 while( obj->running ) {
00114
00115 try{
00116
00117 boost::this_thread::sleep( boost::posix_time::milliseconds(obj->millis) );
00118 if (obj->running)
00119 SystemQueue::instance().scheduleEvent( SystemEvent( obj, TimerEventType, NULL), 0 );
00120
00121 }catch(boost::thread_interrupted e){
00122
00123
00124 }
00125
00126 if( obj->oneshot ) break;
00127 }
00128
00129 if(! obj->oneshot )
00130 obj->running = false;
00131 }
00132 #endif // UNDERLAY_OMNET
00133
00134 void Timer::handleSystemEvent( const SystemEvent& event ) {
00135 if( running ){
00136 if( oneshot ) running = false;
00137 eventFunction();
00138 }
00139
00140 #ifdef UNDERLAY_OMNET
00141 if( ! oneshot && running )
00142 SystemQueue::instance().scheduleEvent(
00143 SystemEvent( this, TimerEventType, NULL), millis );
00144 #endif
00145 }
00146
00147 }}