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 56 return !m_info.expired() && !m_info.lock()->isExpired;
62 return (!(*
this) && !other) ||
63 !(m_info.owner_before(other.m_info) || other.m_info.owner_before(m_info));
69 return os << eventId.m_info.lock();
75 return a->expireTime < b->expireTime;
79 : m_timer(
make_unique<detail::SteadyTimer>(ioService))
80 , m_isEventExecuting(false)
89 BOOST_ASSERT(callback !=
nullptr);
91 EventQueue::iterator i = m_queue.insert(make_shared<EventInfo>(after, callback));
94 if (!m_isEventExecuting && i == m_queue.begin()) {
105 shared_ptr<EventInfo> info = eventId.m_info.lock();
106 if (info ==
nullptr || info->isExpired) {
110 if (info->queueIt == m_queue.begin()) {
113 m_queue.erase(info->queueIt);
115 if (!m_isEventExecuting) {
116 this->scheduleNext();
128 Scheduler::scheduleNext()
130 if (!m_queue.empty()) {
131 m_timer->expires_from_now((*m_queue.begin())->expiresFromNow());
132 m_timer->async_wait(bind(&Scheduler::executeEvent,
this, _1));
137 Scheduler::executeEvent(
const boost::system::error_code& error)
143 m_isEventExecuting =
true;
145 BOOST_SCOPE_EXIT(this_) {
146 this_->m_isEventExecuting =
false;
147 this_->scheduleNext();
148 } BOOST_SCOPE_EXIT_END
152 while (!m_queue.empty()) {
153 auto head = m_queue.begin();
154 shared_ptr<EventInfo> info = *head;
155 if (info->expireTime > now) {
160 info->isExpired =
true;
Copyright (c) 2013-2017 Regents of the University of California.
bool operator()(const shared_ptr< EventInfo > &a, const shared_ptr< EventInfo > &b) const
static time_point now() noexcept
unique_ptr< T > make_unique(Args &&...args)
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)
bool operator==(const EventId &other) const
Identifies a scheduled event.
std::ostream & operator<<(std::ostream &os, const EventId &eventId)