23 #include "ndn-cxx/util/impl/steady-timer.hpp" 25 #include <boost/scope_exit.hpp> 33 class EventInfo : noncopyable
36 EventInfo(time::nanoseconds after,
const EventCallback& callback)
44 expiresFromNow()
const 53 EventQueue::const_iterator queueIt;
57 : CancelHandle([&sched, info] { sched.cancelImpl(info.lock()); })
58 , m_info(std::move(info))
62 EventId::operator bool() const noexcept
64 auto sp = m_info.lock();
65 return sp !=
nullptr && !sp->isExpired;
71 return (!*
this && !other) ||
72 !(m_info.owner_before(other.m_info) || other.m_info.owner_before(m_info));
84 return os << eventId.m_info.lock();
90 return a->expireTime < b->expireTime;
94 : m_timer(make_unique<detail::SteadyTimer>(ioService))
95 , m_isEventExecuting(false)
104 BOOST_ASSERT(callback !=
nullptr);
106 EventQueue::iterator i = m_queue.insert(make_shared<EventInfo>(after, callback));
109 if (!m_isEventExecuting && i == m_queue.begin()) {
111 this->scheduleNext();
118 Scheduler::cancelImpl(
const shared_ptr<EventInfo>& info)
120 if (info ==
nullptr || info->isExpired) {
124 if (info->queueIt == m_queue.begin()) {
127 m_queue.erase(info->queueIt);
129 if (!m_isEventExecuting) {
130 this->scheduleNext();
142 Scheduler::scheduleNext()
144 if (!m_queue.empty()) {
145 m_timer->expires_from_now((*m_queue.begin())->expiresFromNow());
146 m_timer->async_wait([
this] (
const auto& error) { this->executeEvent(error); });
151 Scheduler::executeEvent(
const boost::system::error_code& error)
157 m_isEventExecuting =
true;
159 BOOST_SCOPE_EXIT(this_) {
160 this_->m_isEventExecuting =
false;
161 this_->scheduleNext();
162 } BOOST_SCOPE_EXIT_END
166 while (!m_queue.empty()) {
167 auto head = m_queue.begin();
168 shared_ptr<EventInfo> info = *head;
169 if (info->expireTime > now) {
174 info->isExpired =
true;
void reset() noexcept
Clear this EventId without canceling.
EventId() noexcept=default
Constructs an empty EventId.
static time_point now() noexcept
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)
A handle of scheduled event.
bool operator==(const EventId &other) const noexcept
Determine whether this and other refer to the same event, or are both empty/expired/cancelled.
std::ostream & operator<<(std::ostream &os, const EventId &eventId)
bool operator()(const shared_ptr< EventInfo > &a, const shared_ptr< EventInfo > &b) const noexcept