-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.cpp
80 lines (66 loc) · 1.34 KB
/
timer.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
69
70
71
72
73
74
75
76
77
78
79
80
#include "timer.h"
#include <chrono>
#include <utility>
#include <boost/bind.hpp>
timer_t::timer_t(boost::asio::io_service& service, int period_ms, handler_type handler)
: period_ms_(period_ms), count_(0), limit_(0), is_running_(false)
, handler_(std::move(handler))
, timer_(std::make_shared<boost::asio::steady_timer>(std::ref(service), std::chrono::milliseconds(period_ms)))
{}
int timer_t::period_ms() const
{
return period_ms_;
}
uint64_t timer_t::count() const
{
return count_;
}
uint64_t timer_t::limit() const
{
return limit_;
}
bool timer_t::is_running() const
{
return is_running_;
}
void timer_t::run(uint64_t limit /* = 0 */)
{
if(!is_running_)
{
count_ = 0;
limit_ = limit;
is_running_ = true;
timer_->async_wait(boost::bind(&timer_t::operator(), this, boost::asio::placeholders::error));
}
}
void timer_t::stop()
{
if(is_running_)
{
is_running_ = false;
timer_->cancel();
}
}
void timer_t::operator()(const boost::system::error_code& ec)
{
if(!ec)
{
++count_;
if(handler_)
{
handler_(period_ms_, count_);
}
if(is_running_)
{
if(0 == limit_ || count_ < limit_)
{
timer_->expires_at(timer_->expires_at() + std::chrono::milliseconds(period_ms_));
timer_->async_wait(boost::bind(&timer_t::operator(), this, boost::asio::placeholders::error));
}
else
{
stop();
}
}
}
}