-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimerFunction.hpp
More file actions
110 lines (88 loc) · 2.04 KB
/
TimerFunction.hpp
File metadata and controls
110 lines (88 loc) · 2.04 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#ifndef TIMERFUNCTION_HPP_
# define TIMERFUNCTION_HPP_
# include <chrono>
# include <thread>
# include <functional>
# include <memory>
# include <atomic>
# include <cassert>
# include "Timer.hpp"
class TimerFunction : public Timer<std::chrono::milliseconds>
{
typedef std::function<void ()> func;
public:
TimerFunction():Timer(),
cpt_(0), timetoSleep_(0), continue_(true),
started_(false), stopped_(true)
{}
TimerFunction(func function, int timetoSleep)
:TimerFunction()
{
setFunction(function, timetoSleep);
}
~TimerFunction()
{
if (!stopped_)
{
continue_ = false;
thread_.join();
}
}
void start()
{
assert(started_ == false);
started_ = true;
continue_ = true;
cpt_ = 0;
stopped_ = false;
reset();
thread_ = std::thread(&TimerFunction::run, this);
}
void setFunction(func function, int timetoSleep)
{
assert(timetoSleep > 0);
assert(function != nullptr);
timetoSleep_ = timetoSleep;
func_ = function;
}
void stop()
{
assert(started_ == true);
assert(continue_ == true);
started_ = false;
continue_ = false;
//thread_.detach();
thread_.join();
}
long long itCounts() const
{
return cpt_;
}
bool isRunning() const
{
return thread_.joinable();
}
bool isStopped() const
{
return stopped_;
}
private:
void run()
{
while (continue_)
{
++cpt_;
func_();
sleep(timetoSleep_);
}
stopped_ = true;
}
std::function<void()> func_;
std::atomic<long long int> cpt_;
int timetoSleep_;
std::thread thread_;
std::atomic<bool> continue_;
std::atomic<bool> started_;
std::atomic<bool> stopped_;
};
#endif /* end of include guard */