23 #include "ndn-cxx/util/impl/steady-timer.hpp" 25 #include <boost/scope_exit.hpp> 33 class EventInfo : noncopyable
43 expiresFromNow()
const 50 Scheduler::EventQueue::const_iterator queueIt;
52 bool isExpired =
false;
56 : CancelHandle([&sched, info] { sched.cancelImpl(info.lock()); })
61 EventId::operator bool() const noexcept
63 auto sp = m_info.lock();
64 return sp !=
nullptr && !sp->isExpired;
70 return (!*
this && !other) ||
71 !(m_info.owner_before(other.m_info) || other.m_info.owner_before(m_info));
83 return os << eventId.m_info.lock();
87 Scheduler::EventQueueCompare::operator()(
const shared_ptr<EventInfo>& a,
88 const shared_ptr<EventInfo>& b)
const noexcept
90 return a->expireTime < b->expireTime;
94 : m_timer(make_unique<detail::SteadyTimer>(ioService))
103 BOOST_ASSERT(callback !=
nullptr);
105 auto i = m_queue.insert(make_shared<EventInfo>(after,
std::move(callback)));
108 if (!m_isEventExecuting && i == m_queue.begin()) {
110 this->scheduleNext();
117 Scheduler::cancelImpl(
const shared_ptr<EventInfo>& info)
119 if (info ==
nullptr || info->isExpired) {
123 if (info->queueIt == m_queue.begin()) {
126 m_queue.erase(info->queueIt);
128 if (!m_isEventExecuting) {
129 this->scheduleNext();
141 Scheduler::scheduleNext()
143 if (!m_queue.empty()) {
144 m_timer->expires_from_now((*m_queue.begin())->expiresFromNow());
145 m_timer->async_wait([
this] (
const auto& error) { this->executeEvent(error); });
150 Scheduler::executeEvent(
const boost::system::error_code& error)
156 m_isEventExecuting =
true;
158 BOOST_SCOPE_EXIT(this_) {
159 this_->m_isEventExecuting =
false;
160 this_->scheduleNext();
161 } BOOST_SCOPE_EXIT_END
165 while (!m_queue.empty()) {
166 auto head = m_queue.begin();
167 shared_ptr<EventInfo> info = *head;
168 if (info->expireTime > now) {
173 info->isExpired =
true;
void reset() noexcept
Clear this EventId without canceling.
Generic time-based scheduler.
EventId() noexcept=default
Constructs an empty EventId.
static time_point now() noexcept
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)
EventId schedule(time::nanoseconds after, EventCallback callback)
Schedule a one-time event after the specified delay.
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)