timer.h
Go to the documentation of this file.
1 #ifndef H_CANOPEN_TIMER
2 #define H_CANOPEN_TIMER
3 
5 #include <boost/asio.hpp>
6 #include <boost/thread/thread.hpp>
7 #include <boost/asio/high_resolution_timer.hpp>
8 
9 namespace canopen{
10 
11 class Timer{
12 public:
14  Timer():work(io), timer(io),thread(fastdelegate::FastDelegate0<size_t>(&io, &boost::asio::io_service::run)){
15  }
16 
17  void stop(){
18  boost::mutex::scoped_lock lock(mutex);
19  timer.cancel();
20  }
21  template<typename T> void start(const TimerDelegate &del, const T &dur, bool start_now = true){
22  boost::mutex::scoped_lock lock(mutex);
23  delegate = del;
24  period = boost::chrono::duration_cast<boost::chrono::high_resolution_clock::duration>(dur);
25  if(start_now){
26  timer.expires_from_now(period);
28  }
29  }
30  void restart(){
31  boost::mutex::scoped_lock lock(mutex);
32  timer.expires_from_now(period);
34  }
35  const boost::chrono::high_resolution_clock::duration & getPeriod(){
36  boost::mutex::scoped_lock lock(mutex);
37  return period;
38  }
39  ~Timer(){
40  io.stop();
41  thread.join();
42  }
43 
44 private:
45  boost::asio::io_service io;
46  boost::asio::io_service::work work;
47  boost::asio::basic_waitable_timer<boost::chrono::high_resolution_clock> timer;
48  boost::chrono::high_resolution_clock::duration period;
49  boost::mutex mutex;
50  boost::thread thread;
51 
52  TimerDelegate delegate;
53  void handler(const boost::system::error_code& ec){
54  if(!ec){
55  boost::mutex::scoped_lock lock(mutex);
56  if(delegate && delegate()){
57  timer.expires_at(timer.expires_at() + period);
59  }
60 
61  }
62  }
63 };
64 
65 }
66 
67 #endif
boost::asio::io_service io
Definition: timer.h:45
TimerDelegate delegate
Definition: timer.h:52
boost::mutex mutex
Definition: timer.h:49
void start(const TimerDelegate &del, const T &dur, bool start_now=true)
Definition: timer.h:21
boost::thread thread
Definition: timer.h:50
void handler(const boost::system::error_code &ec)
Definition: timer.h:53
const boost::chrono::high_resolution_clock::duration & getPeriod()
Definition: timer.h:35
void stop()
Definition: timer.h:17
boost::asio::basic_waitable_timer< boost::chrono::high_resolution_clock > timer
Definition: timer.h:47
void restart()
Definition: timer.h:30
void run(ClassLoader *loader)
boost::chrono::high_resolution_clock::duration period
Definition: timer.h:48
boost::asio::io_service::work work
Definition: timer.h:46
fastdelegate::FastDelegate0< bool > TimerDelegate
Definition: timer.h:13


canopen_master
Author(s): Mathias Lüdtke
autogenerated on Fri May 14 2021 02:59:41