Utilities
Utilities header only library
CallbackTimer.h
1 /*
2  Copyright (C) Skeletex Research, s.r.o. - All Rights Reserved
3  Unauthorized copying of this file, via any medium is strictly prohibited
4  Proprietary and confidential
5 */
6 #ifndef UTILS_CALLBACK_TIMER_H
7 #define UTILS_CALLBACK_TIMER_H
8 
9 #include <atomic>
10 #include <thread>
11 
12 #include <Utils/Threading.h>
13 
14 
15 
16 namespace utils
17 {
18  /*
19  \brief
20  An async timer executes given function every time interval.
21  \note
22  Runs every time interval until callback either returns false or the timer is stopped.
23  Accepts only a single callback. Running Start with a new callback stops the old one.
24  */
25  class CallbackTimer
26  {
27  public:
29  CallbackTimer()
30  : execute_(false)
31  {}
32 
34  ~CallbackTimer()
35  {
36  if (execute_.load(std::memory_order_acquire))
37  {
38  Stop();
39  };
40  }
41 
52  template<typename DurationType>
53  void Start(DurationType interval, std::function<bool(void)> callback)
54  {
55  if (execute_.load(std::memory_order_acquire))
56  {
57  Stop();
58  };
59 
60  execute_.store(true, std::memory_order_release);
61  thread_ = std::thread([this, interval, callback]()
62  {
63  utils::SetThisThreadName("CallbackTimer_thread");
64  while (execute_.load(std::memory_order_acquire))
65  {
66  execute_.store(callback(), std::memory_order_release);
67  std::this_thread::sleep_for(interval);
68  }
69  });
70  }
71 
73  void Stop()
74  {
75  execute_.store(false, std::memory_order_release);
76  if (thread_.joinable())
77  {
78  thread_.join();
79  }
80  }
81 
83  bool IsRunning() const noexcept
84  {
85  return (execute_.load(std::memory_order_acquire) && thread_.joinable());
86  }
87 
88  private:
90  std::atomic<bool> execute_;
92  std::thread thread_;
93  };
94 }
95 
96 #endif /* !UTILS_CALLBACK_TIMER_H */
General namespace for utilities.
Definition: BulletConversions.h:9