-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIntervalRunner.h
60 lines (53 loc) · 1.86 KB
/
IntervalRunner.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#pragma once
#include <functional>
#include <thread>
#include <memory>
#include <utility>
#include <chrono>
class IntervalRunner {
public:
IntervalRunner(std::function<void()> toRun, std::chrono::milliseconds runEvery,
std::chrono::milliseconds firstDelay,
bool singleRun = false, bool alwaysWait = false) : toRun(std::move(toRun)), runEvery(runEvery),
firstDelay(firstDelay),
singleRun(singleRun), alwaysWait(alwaysWait) {}
~IntervalRunner(){
Stop();
Join();
}
void Run() {
running = true;
mainThread = std::make_unique<std::thread>([&] {
std::this_thread::sleep_for(firstDelay);
do {
this->start = std::chrono::system_clock::now();
this->toRun();
this->end = std::chrono::system_clock::now();
this->nextRun = this->alwaysWait ? this->runEvery :
std::chrono::duration_cast<std::chrono::milliseconds>(
this->runEvery + this->start - this->end);
std::this_thread::sleep_for(this->nextRun);
} while (!singleRun);
this->running = false;
});
}
void Stop() {
singleRun = true;
}
void Join() {
mainThread->join();
}
bool isRunning() {
return this->running;
}
private:
std::function<void()> toRun;
std::chrono::milliseconds runEvery;
std::chrono::milliseconds firstDelay;
std::chrono::milliseconds nextRun;
bool running = false;
bool singleRun = false;
bool alwaysWait = false;
std::unique_ptr<std::thread> mainThread;
std::chrono::time_point<std::chrono::system_clock> start, end;
};