23 #include "ndn-cxx/util/impl/steady-timer.hpp" 31 class EventInfo : noncopyable
35 : callback(std::move(cb))
41 expiresFromNow()
const 48 Scheduler::EventQueue::const_iterator queueIt;
50 bool isExpired =
false;
54 : CancelHandle([&sched, info] { sched.cancelImpl(info.lock()); })
55 , m_info(std::move(info))
59 EventId::operator bool() const noexcept
61 auto sp = m_info.lock();
62 return sp !=
nullptr && !sp->isExpired;
74 return os << eventId.m_info.lock();
78 Scheduler::EventQueueCompare::operator()(
const shared_ptr<EventInfo>& a,
79 const shared_ptr<EventInfo>& b)
const noexcept
81 return a->expireTime < b->expireTime;
85 : m_timer(make_unique<util::detail::SteadyTimer>(ioService))
94 BOOST_ASSERT(callback !=
nullptr);
96 auto i = m_queue.insert(std::make_shared<EventInfo>(after, std::move(callback)));
99 if (!m_isEventExecuting && i == m_queue.begin()) {
108 Scheduler::cancelImpl(
const shared_ptr<EventInfo>& info)
110 if (info ==
nullptr || info->isExpired) {
114 if (info->queueIt == m_queue.begin()) {
117 m_queue.erase(info->queueIt);
119 if (!m_isEventExecuting) {
132 Scheduler::scheduleNext()
134 if (!m_queue.empty()) {
135 m_timer->expires_from_now((*m_queue.begin())->expiresFromNow());
136 m_timer->async_wait([
this] (
const auto& error) { this->executeEvent(error); });
141 Scheduler::executeEvent(
const boost::system::error_code& error)
147 auto guard = make_scope_exit([
this] {
148 m_isEventExecuting =
false;
151 m_isEventExecuting =
true;
155 while (!m_queue.empty()) {
156 auto head = m_queue.begin();
157 shared_ptr<EventInfo> info = *head;
158 if (info->expireTime > now) {
163 info->isExpired =
true;
void reset() noexcept
Clear this EventId without canceling.
std::function< void()> EventCallback
Function to be invoked when a scheduled event expires.
static time_point now() noexcept
EventId schedule(time::nanoseconds after, EventCallback callback)
Schedule a one-time event after the specified delay.
A handle for a scheduled event.
EventId() noexcept=default
Constructs an empty EventId.
std::ostream & operator<<(std::ostream &os, const EventId &eventId)
#define NDN_CXX_NODISCARD
Generic time-based scheduler.
Scheduler(boost::asio::io_service &ioService)
void cancelAllEvents()
Cancel all scheduled events.