IBR-DTNSuite  0.10
Timer.cpp
Go to the documentation of this file.
1 /*
2  * Timer.cpp
3  *
4  * Copyright (C) 2011 IBR, TU Braunschweig
5  *
6  * Written-by: Johannes Morgenroth <morgenroth@ibr.cs.tu-bs.de>
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  */
21 
22 #include "ibrcommon/config.h"
23 #include "ibrcommon/thread/Timer.h"
25 
26 #include <iostream>
27 #include <queue>
28 #include <utility>
29 #include <sstream>
30 
31 namespace ibrcommon
32 {
34  {
35  ::time_t rawtime = ::time(NULL);
36  tm * ptm;
37 
38  ptm = ::gmtime ( &rawtime );
39 
40  return ::mktime(ptm);
41  }
42 
43  Timer::Timer(TimerCallback &callback, size_t timeout)
44  : _state(TIMER_UNSET), _callback(callback), _timeout(timeout * 1000)
45  {
46  }
47 
49  {
50  stop();
51  join();
52  }
53 
54  void Timer::__cancellation() throw ()
55  {
56  MutexLock l(_state);
57  _state.setState(TIMER_CANCELLED);
58  _state.abort();
59  }
60 
61  void Timer::set(size_t timeout)
62  {
63  MutexLock l(_state);
64  _timeout = timeout * 1000;
65  _state.setState(TIMER_RESET);
66  }
67 
68  void Timer::reset()
69  {
70  MutexLock l(_state);
71  _state.setState(TIMER_RESET);
72  }
73 
74  void Timer::pause()
75  {
76  MutexLock l(_state);
77  _state.setState(TIMER_STOPPED);
78  }
79 
80  size_t Timer::getTimeout() const
81  {
82  return _timeout / 1000;
83  }
84 
85  void Timer::run() throw ()
86  {
87  MutexLock l(_state);
88  _state.setState(TIMER_RUNNING);
89 
90  while (_state.ifState(TIMER_RUNNING) || _state.ifState(TIMER_STOPPED))
91  {
92  try {
93  if(_state.ifState(TIMER_RUNNING))
94  {
95  if(_timeout > 0)
96  {
97  _state.wait(_timeout);
98  }
99  else
100  {
102  }
103  }
104  else
105  {
106  _state.wait();
107  }
108 
109  // got signal, check for reset request
110  if (_state.ifState(TIMER_RESET))
111  {
112  _state.setState(TIMER_RUNNING);
113  }
114  else if(!_state.ifState(TIMER_STOPPED))
115  {
116  // stop the timer
117  _state.setState(TIMER_CANCELLED);
118  }
119  }
121  {
122  switch (ex.reason)
123  {
125  {
126  try
127  {
128  // timeout exceeded, call callback method
129  _timeout = _callback.timeout(this) * 1000;
130  _state.setState(TIMER_RUNNING);
131  }
132  catch(const StopTimerException &ex)
133  {
134  // stop the timer
135  _state.setState(TIMER_STOPPED);
136  }
137  break;
138  }
139 
142  {
143  _state.setState(TIMER_CANCELLED);
144  return;
145  }
146  }
147  }
148 
149  yield();
150  }
151  }
152 }