23 #include "detail/steady-timer.hpp" 25 #include <boost/scope_exit.hpp> 31 class EventInfo : noncopyable
34 EventInfo(time::nanoseconds after,
const EventCallback& callback)
35 : expireTime(time::steady_clock::now() + after)
42 expiresFromNow()
const 51 EventQueue::const_iterator queueIt;
54 EventId::operator bool() const noexcept
56 auto sp = m_info.lock();
57 return sp !=
nullptr && !sp->isExpired;
63 return (!*
this && !other) ||
64 !(m_info.owner_before(other.m_info) || other.m_info.owner_before(m_info));
70 return os << eventId.m_info.lock();
76 return a->expireTime < b->expireTime;
80 : m_timer(make_unique<detail::SteadyTimer>(ioService))
81 , m_isEventExecuting(false)
90 BOOST_ASSERT(callback !=
nullptr);
92 EventQueue::iterator i = m_queue.insert(make_shared<EventInfo>(after, callback));
95 if (!m_isEventExecuting && i == m_queue.begin()) {
106 shared_ptr<EventInfo> info = eventId.m_info.lock();
107 if (info ==
nullptr || info->isExpired) {
111 if (info->queueIt == m_queue.begin()) {
114 m_queue.erase(info->queueIt);
116 if (!m_isEventExecuting) {
117 this->scheduleNext();
129 Scheduler::scheduleNext()
131 if (!m_queue.empty()) {
132 m_timer->expires_from_now((*m_queue.begin())->expiresFromNow());
133 m_timer->async_wait([
this] (
const auto& error) { this->executeEvent(error); });
138 Scheduler::executeEvent(
const boost::system::error_code& error)
144 m_isEventExecuting =
true;
146 BOOST_SCOPE_EXIT(this_) {
147 this_->m_isEventExecuting =
false;
148 this_->scheduleNext();
149 } BOOST_SCOPE_EXIT_END
153 while (!m_queue.empty()) {
154 auto head = m_queue.begin();
155 shared_ptr<EventInfo> info = *head;
156 if (info->expireTime > now) {
161 info->isExpired =
true;
Copyright (c) 2013-2017 Regents of the University of California.
static time_point now() noexcept
void cancelEvent(const EventId &eventId)
Cancel a scheduled event.
EventId scheduleEvent(time::nanoseconds after, const EventCallback &callback)
Schedule a one-time event after the specified delay.
void cancelAllEvents()
Cancel all scheduled events.
std::function< void()> EventCallback
Function to be invoked when a scheduled event expires.
Scheduler(boost::asio::io_service &ioService)
Identifies a scheduled event.
bool operator==(const EventId &other) const noexcept
std::ostream & operator<<(std::ostream &os, const EventId &eventId)
bool operator()(const shared_ptr< EventInfo > &a, const shared_ptr< EventInfo > &b) const noexcept