-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperiodic.h
49 lines (43 loc) · 1.08 KB
/
periodic.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
#include <iostream>
#include <thread>
#include <functional>
#include <atomic>
#include <chrono>
class PeriodicRunner
{
public:
PeriodicRunner() : running(false) {}
// Starts running the given function periodically at the given microsecond interval
void start(std::function<void()> func, std::chrono::microseconds interval)
{
if (running.load())
{
std::cout << "Periodic runner is already running.\n";
return;
}
running.store(true);
worker = std::thread([this, func, interval]()
{
while (running.load()) {
auto next_run = std::chrono::steady_clock::now() + interval;
func();
std::this_thread::sleep_until(next_run);
} });
}
// Stops the periodic execution
void stop()
{
running.store(false);
if (worker.joinable())
{
worker.join();
}
}
~PeriodicRunner()
{
stop();
}
private:
std::atomic<bool> running;
std::thread worker;
};