23 #include "ndn-cxx/util/impl/steady-timer.hpp" 25 #include <boost/scope_exit.hpp> 32 class EventInfo : noncopyable
42 expiresFromNow()
const 49 Scheduler::EventQueue::const_iterator queueIt;
51 bool isExpired =
false;
55 : CancelHandle([&sched, info] { sched.cancelImpl(info.lock()); })
60 EventId::operator bool() const noexcept
62 auto sp = m_info.lock();
63 return sp !=
nullptr && !sp->isExpired;
75 return os << eventId.m_info.lock();
79 Scheduler::EventQueueCompare::operator()(
const shared_ptr<EventInfo>& a,
80 const shared_ptr<EventInfo>& b)
const noexcept
82 return a->expireTime < b->expireTime;
86 : m_timer(make_unique<util::detail::SteadyTimer>(ioService))
95 BOOST_ASSERT(callback !=
nullptr);
97 auto i = m_queue.insert(make_shared<EventInfo>(after,
std::move(callback)));
100 if (!m_isEventExecuting && i == m_queue.begin()) {
102 this->scheduleNext();
109 Scheduler::cancelImpl(
const shared_ptr<EventInfo>& info)
111 if (info ==
nullptr || info->isExpired) {
115 if (info->queueIt == m_queue.begin()) {
118 m_queue.erase(info->queueIt);
120 if (!m_isEventExecuting) {
121 this->scheduleNext();
133 Scheduler::scheduleNext()
135 if (!m_queue.empty()) {
136 m_timer->expires_from_now((*m_queue.begin())->expiresFromNow());
137 m_timer->async_wait([
this] (
const auto& error) { this->executeEvent(error); });
142 Scheduler::executeEvent(
const boost::system::error_code& error)
148 m_isEventExecuting =
true;
150 BOOST_SCOPE_EXIT(this_) {
151 this_->m_isEventExecuting =
false;
152 this_->scheduleNext();
153 } BOOST_SCOPE_EXIT_END
157 while (!m_queue.empty()) {
158 auto head = m_queue.begin();
159 shared_ptr<EventInfo> info = *head;
160 if (info->expireTime > now) {
165 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.