TimerThread.h
1 #pragma once
2 
3 #include "stormancer/BuildConfig.h"
4 #include <thread>
5 #include <condition_variable>
6 #include <mutex>
7 #include <queue>
8 #include <chrono>
9 #include <functional>
10 #include <memory>
11 
12 namespace Stormancer
13 {
14  class IActionDispatcher;
15 
17  {
18  public:
19 
20  using clock_type = std::chrono::steady_clock;
21 
22 #pragma region public_methods
23 
24  static TimerThread& getInstance();
25 
26  TimerThread();
27 
28  ~TimerThread();
29 
30  TimerThread(const TimerThread&) = delete;
31 
38  void schedule(std::function<void()> func, clock_type::time_point when, std::shared_ptr<IActionDispatcher> dispatcher = nullptr);
39 
40 #pragma endregion
41 
42  private:
43 
44  struct QueueEntry
45  {
46  clock_type::time_point scheduledTime;
47  std::function<void()> function;
48  std::shared_ptr<IActionDispatcher> dispatcher;
49 
50  QueueEntry(clock_type::time_point t, std::function<void()> f, std::shared_ptr<IActionDispatcher> d)
51  : scheduledTime(t)
52  , function(f)
53  , dispatcher(d)
54  {
55  }
56 
57  friend bool operator>(const QueueEntry& lhs, const QueueEntry& rhs)
58  {
59  return lhs.scheduledTime > rhs.scheduledTime;
60  }
61  };
62 
63  using func_queue_type = std::priority_queue<QueueEntry, std::vector<QueueEntry>, std::greater<QueueEntry>>;
64 
65 #pragma region private_methods
66 
67  void _threadLoop();
68 
69  void _stop(bool immediate = false);
70 
71 #pragma endregion
72 
73 #pragma region private_members
74 
75  static std::unique_ptr<TimerThread> _sInstance;
76 
77  std::mutex _mutex;
78  std::condition_variable _cond;
79  func_queue_type _taskQueue;
80  bool _stopRequested = false;
81  std::thread _thread;
82 
83 #pragma endregion
84  };
85 }
void schedule(std::function< void()> func, clock_type::time_point when, std::shared_ptr< IActionDispatcher > dispatcher=nullptr)
Set a function to be executed at the given time point.
Definition: TimerThread.h:16