-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.hpp
49 lines (40 loc) · 1013 Bytes
/
timer.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
#pragma once
#include <chrono>
#include <functional>
#include <mutex>
#include <thread>
#include <atomic>
class Timer final {
public:
Timer(size_t sleepMilliseconds, const std::function<void()>& callback)
: _stop(false)
, _thread([&] {
using namespace std::chrono;
const auto start = system_clock::now();
while (true) {
const auto duration = duration_cast<milliseconds>(system_clock::now() - start).count();
if (duration >= sleepMilliseconds) {
callback();
break;
}
std::this_thread::sleep_for(milliseconds(1));
// Manual stop, callback is not called
if (_stop) {
break;
}
}
})
{
}
void stop()
{
_stop = true;
}
void join()
{
_thread.join();
}
private:
std::atomic_bool _stop;
std::thread _thread;
};