LIPH's C++ Codes
timer.h
Go to the documentation of this file.
1#ifndef LIPH_TIMER_H_
2#define LIPH_TIMER_H_
3
4#include <functional>
5#include <queue>
6#include <thread>
7
9
10namespace liph {
11
12class timer {
13public:
14 timer() {}
15 ~timer() { stop(); }
16
17 void start() {
18 running_ = true;
19 thread_ = std::thread([&]() {
20 int current_time = 0;
21 while (running_) {
22 std::unique_lock lock(lock_);
23 if (queue_.empty()) {
24 unique_unlock unlock(lock);
25 std::this_thread::sleep_for(std::chrono::seconds(1));
26 continue;
27 }
28
29 job j = std::move(queue_.top());
30 queue_.pop();
31 unique_unlock unlock(lock);
32
33 int sleep_time = j.next_time - current_time;
34 if (sleep_time > 0) std::this_thread::sleep_for(std::chrono::seconds(sleep_time));
35 current_time = j.next_time;
36
37 if (j.task) {
38 j.task();
39 j.next_time += j.interval_time;
40 add(std::move(j));
41 }
42 }
43 });
44 }
45
46 void stop() {
47 running_ = false;
48 if (thread_.joinable()) thread_.join();
49 }
50
51 template <class Function, class... Args>
52 void add(int interval, Function&& func, Args&&...args) {
53 add(job{0, interval, std::bind(func, std::forward<Args>(args)...)});
54 }
55
56private:
57 struct job {
58 int next_time;
59 int interval_time;
60 std::function<void()> task;
61
62 bool operator<(const job& other) const { return next_time > other.next_time; }
63 };
64
65 void add(job j) {
66 std::unique_lock lock(lock_);
67 queue_.push(std::move(j));
68 }
69
70 std::priority_queue<job> queue_;
71 std::thread thread_;
72 std::mutex lock_;
73 std::atomic<bool> running_;
74};
75
76} // namespace liph
77
78#endif // LIPH_TIMER_H_
#define func(V)
Definition: timer.h:12
void stop()
Definition: timer.h:46
~timer()
Definition: timer.h:15
timer()
Definition: timer.h:14
void start()
Definition: timer.h:17
void add(int interval, Function &&func, Args &&...args)
Definition: timer.h:52
Definition: lock.h:84
Definition: algorithm.h:10