Repository navigation
Expand file tree
/
Copy pathtask_timer.h
More file actions
87 lines (75 loc) · 1.63 KB
/
Copy pathtask_timer.h
File metadata and controls
87 lines (75 loc) · 1.63 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
#pragma once
#include <vector>
#include <thread>
#include <atomic>
#include <functional>
#include <boost/timer.hpp>
#include <boost/asio.hpp>
template<typename Duration = boost::posix_time::milliseconds>
class task_timer
{
public:
task_timer() : work_(ios_), timer_(ios_) {}
~task_timer()
{
destroy();
}
void start(std::size_t duration)
{
if (ios_.stopped())
{
return;
}
duration_ = duration;
thread_ = std::thread([this]{ ios_.run(); });
start();
}
void start()
{
timer_.expires_from_now(Duration(duration_));
timer_.async_wait([this](const boost::system::error_code& ec)
{
if (ec)
{
return;
}
for (auto& func : func_vec_)
{
func();
}
if (!is_single_shot_)
{
start();
}
});
}
void stop()
{
timer_.cancel();
}
void destroy()
{
stop();
ios_.stop();
if (thread_.joinable())
{
thread_.join();
}
}
void bind(const std::function<void()>& func)
{
func_vec_.emplace_back(func);
}
void set_single_shot(bool is_single_shot)
{
is_single_shot_ = is_single_shot;
}
private:
boost::asio::io_service ios_;
boost::asio::io_service::work work_;
boost::asio::deadline_timer timer_;
std::vector<std::function<void()>> func_vec_;
std::thread thread_;
std::size_t duration_ = 0;
std::atomic<bool> is_single_shot_ { false };
};