-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntervalTimer.cpp
More file actions
57 lines (40 loc) · 1018 Bytes
/
Copy pathIntervalTimer.cpp
File metadata and controls
57 lines (40 loc) · 1018 Bytes
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
#include "IntervalTimer.hpp"
namespace framework
{
IntervalTimer::IntervalTimer() : m_running(false), m_period(std::chrono::microseconds::rep{ 0 })
{
}
IntervalTimer::IntervalTimer(const std::chrono::milliseconds period) : m_period(period), m_running(false)
{
}
IntervalTimer::~IntervalTimer()
{
stop();
}
void IntervalTimer::start(std::function<void()> callback, const std::chrono::milliseconds period)
{
m_period = period;
start(callback);
}
void IntervalTimer::start(std::function<void()> callback)
{
m_callback = callback;
m_running.store(true);
m_future = std::async(std::launch::async, [this]
{
while (m_running.load())
{
std::unique_lock lock(m_mux);
if (!m_cv.wait_for(lock, m_period, [this] { return m_running.load() == false; }))
m_callback();
}
});
}
void IntervalTimer::stop()
{
m_running.store(false);
m_cv.notify_one();
if (m_future.valid())
m_future.wait();
}
}