-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer_test.cpp
70 lines (53 loc) · 1.17 KB
/
timer_test.cpp
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
#include <stdio.h>
#include <iostream>
#include <thread>
using std::cout;
using std::endl;
class Timer {
bool clear = false;
public:
template<typename Function>
void setTimeout(Function function, int delay);
template<typename Function>
void setInterval(Function function, int interval);
void stop();
};
template<typename Function>
void Timer::setTimeout(Function function, int delay) {
this->clear = false;
std::thread t([=]() {
if (this->clear) return;
std::this_thread::sleep_for(std::chrono::milliseconds(delay));
if (this->clear) return;
function();
});
t.detach();
}
template<typename Function>
void Timer::setInterval(Function function, int interval) {
this->clear = false;
std::thread t([=]() {
while (true) {
if (this->clear) return;
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
if (this->clear) return;
function();
}
});
t.detach();
}
void Timer::stop() {
this->clear = true;
}
int main(){
Timer t = Timer();
t.setInterval([&]() {
cout << "Hey.. After each 1s..." << endl;
}, 1000);
t.setTimeout([&]() {
cout << "Hey.. After 5.2s. But I will stop the timer!" << endl;
t.stop();
}, 5200);
while (1){
}
}