-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathtimercpp.h
41 lines (35 loc) · 904 Bytes
/
timercpp.h
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
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
class Timer {
std::atomic<bool> active{true};
public:
void setTimeout(auto function, int delay);
void setInterval(auto function, int interval);
void stop();
};
void Timer::setTimeout(auto function, int delay) {
active = true;
std::thread t([=]() {
if(!active.load()) return;
std::this_thread::sleep_for(std::chrono::milliseconds(delay));
if(!active.load()) return;
function();
});
t.detach();
}
void Timer::setInterval(auto function, int interval) {
active = true;
std::thread t([=]() {
while(active.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
if(!active.load()) return;
function();
}
});
t.detach();
}
void Timer::stop() {
active = false;
}