-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSimpleTimer.hpp
124 lines (106 loc) · 2.55 KB
/
SimpleTimer.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
//
// Created by Richard on 7/30/2019.
//
#ifndef SIMPLETIMER_SIMPLETIMER_HPP
#define SIMPLETIMER_SIMPLETIMER_HPP
#include <iostream>
#include <chrono>
#include <functional>
#include <thread>
/**
* Create asynchronous timers which execute specified
* functions in set time interval.
*
* @param func Function which should be executed
* @param interval Interval of time in which function will be executed
* (in milliseconds)
*/
class Timer {
public:
Timer() {}
Timer(std::function<void(void)> func, const long &interval) {
m_func = func;
m_interval = interval;
}
/**
* Starting the timer.
*/
void start() {
m_running = true;
m_thread = std::thread([&]() {
while (m_running) {
auto delta = std::chrono::steady_clock::now() + std::chrono::milliseconds(m_interval);
m_func();
std::this_thread::sleep_until(delta);
}
});
m_thread.detach();
}
/*
* Stopping the timer and destroys the thread.
*/
void stop() {
m_running = false;
m_thread.~thread();
}
/*
* Restarts the timer. Needed if you set a new
* timer interval for example.
*/
void restart() {
stop();
start();
}
/*
* Check if timer is running.
*
* @returns boolean is running
*/
bool isRunning() {
return m_running;
}
/*
* Set the method of the timer after
* initializing the timer instance.
*
* @returns boolean is running
* @return Timer reference of this
*/
Timer *setFunc(std::function<void(void)> func) {
m_func = func;
return this;
}
/*
* Returns the current set interval in milliseconds.
*
* @returns long interval
*/
long getInterval() {
return m_interval;
}
/*
* Set a new interval for the timer in milliseconds.
* This change will be valid only after restarting
* the timer.
*
* @param interval new interval
* @return Timer reference of this
*/
Timer *setInterval(const long &interval) {
m_interval = interval;
return this;
}
~Timer() {
stop();
}
private:
// Function to be executed after interval
std::function<void(void)> m_func;
// Timer interval in milliseconds
long m_interval;
// Thread timer is running into
std::thread m_thread;
// Status if timer is running
bool m_running = false;
};
#endif //SIMPLETIMER_SIMPLETIMER_HPP