-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRepeatedTask.cpp
68 lines (56 loc) · 1.68 KB
/
RepeatedTask.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
#include "RepeatedTask.h"
///-------------------------------------------------------------------------------------------------
/// @fn template<class T> RepeatedTask::RepeatedTask(function<T>& f)
///
/// @brief Constructor
///
/// @author Benjamin
/// @date 28.09.2020
///
/// @tparam T Generic type parameter.
/// @param [in,out] f A function<T> to process.
RepeatedTask::RepeatedTask(const function<void()>& f, const chrono::steady_clock::duration& waitTime) :
waitTime(waitTime), f(f) {
}
///-------------------------------------------------------------------------------------------------
/// @fn void RepeatedTask::setWaitTime(chrono::steady_clock::duration waitTime)
///
/// @brief Sets wait time
///
/// @author Benjamin
/// @date 01.10.2020
///
/// @param waitTime The wait time.
void RepeatedTask::start() {
t = thread([](const function<void()>& f, RepeatedTask* rt) {
while (!rt->getShouldStop()) {
//cout << "Executing repeated task" << endl;
f();
this_thread::sleep_for(rt->getWaitTime());
}
}, f, this);
t.detach();
}
void RepeatedTask::setWaitTime(const chrono::steady_clock::duration& waitTime) {
this->waitTime = waitTime;
}
chrono::steady_clock::duration RepeatedTask::getWaitTime() const {
return waitTime;
}
///-------------------------------------------------------------------------------------------------
/// @fn void RepeatedTask::stop()
///
/// @brief Stops the repeating task at the next opportunity and joins it with the current thread
///
/// @author Benjamin
/// @date 28.09.2020
void RepeatedTask::stop() {
shouldStop = true;
t.join();
}
bool RepeatedTask::getShouldStop() const {
return shouldStop;
}
RepeatedTask::~RepeatedTask() {
stop();
}