PeriodicTimer.cpp
Go to the documentation of this file.
1 #include "PeriodicTimer.hpp"
2 
3 namespace msp {
4 
5 PeriodicTimer::PeriodicTimer(std::function<void()> funct,
6  const double period_seconds) :
7  funct(funct) {
8  period_us =
9  std::chrono::duration<size_t, std::micro>(size_t(period_seconds * 1e6));
10 }
11 
13  // only start thread if period is above 0
14  if(!(period_us.count() > 0)) return false;
15  // only start once
16  if(running_.test_and_set()) return false;
17  // lock mutex so that the try_lock_until in the new thread always times out
18  // and loops
19  mutex_timer.lock();
20  // start the thread
21  thread_ptr = std::shared_ptr<std::thread>(new std::thread([this] {
22  // log now.
23  tstart = std::chrono::steady_clock::now();
24  while(true) {
25  // call function
26  funct();
27  // increment the reference time to know when to timeout waiting
28  tstart += period_us;
29  // wait until end of period or stop is called
30  if(mutex_timer.try_lock_until(tstart)) {
31  // gets here if lock was acquired (means someone called stop and
32  // manually unlocked the mutex)
33  mutex_timer.unlock();
34  break;
35  }
36  } // function over, return
37  }));
38  return true;
39 }
40 
42  bool rc = false;
43  if(running_.test_and_set()) {
44  // was already running, so let the thread finish
45  mutex_timer.unlock();
46  if(thread_ptr != nullptr && thread_ptr->joinable()) {
47  thread_ptr->join();
48  }
49  rc = true;
50  }
51  running_.clear();
52  return rc;
53 }
54 
55 void PeriodicTimer::setPeriod(const double& period_seconds) {
56  stop();
57  period_us =
58  std::chrono::duration<size_t, std::micro>(size_t(period_seconds * 1e6));
59  start();
60 }
61 
62 } // namespace msp
bool start()
start define and start background thread
std::atomic_flag running_
bool stop()
stop tell thread to stop and wait for end
std::function< void()> funct
void setPeriod(const double &period_seconds)
setPeriod change the update period of timer thread This will stop and restart the thread...
std::shared_ptr< std::thread > thread_ptr
std::chrono::duration< size_t, std::micro > period_us
std::timed_mutex mutex_timer
std::chrono::steady_clock::time_point tstart
PeriodicTimer(const std::function< void()> funct, const double period_seconds)
PeriodicTimer define a periodic timer.


msp
Author(s): Christian Rauch
autogenerated on Tue Oct 6 2020 03:39:02