23 #include "ndn-cxx/util/impl/steady-timer.hpp"
31 struct EventInfo : noncopyable
35 , callback(std::move(cb))
41 Scheduler::EventQueue::const_iterator queueIt;
42 bool isExpired =
false;
46 : CancelHandle([&sched,
info] { sched.cancelImpl(
info.lock()); })
47 , m_info(std::move(
info))
51 EventId::operator bool() const noexcept
53 auto sp = m_info.lock();
54 return sp !=
nullptr && !sp->isExpired;
64 Scheduler::EventQueueCompare::operator()(
const shared_ptr<EventInfo>& a,
65 const shared_ptr<EventInfo>& b)
const noexcept
67 return a->expiry < b->expiry;
71 : m_timer(make_unique<detail::SteadyTimer>(ioCtx))
80 BOOST_ASSERT(callback !=
nullptr);
82 auto i = m_queue.insert(std::make_shared<EventInfo>(after, std::move(callback)));
85 if (!m_isEventExecuting && i == m_queue.begin()) {
94 Scheduler::cancelImpl(
const shared_ptr<EventInfo>&
info)
96 if (
info ==
nullptr ||
info->isExpired) {
100 if (
info->queueIt == m_queue.begin()) {
103 m_queue.erase(
info->queueIt);
105 if (!m_isEventExecuting) {
118 Scheduler::scheduleNext()
120 if (!m_queue.empty()) {
121 m_timer->expires_at((*m_queue.begin())->expiry);
122 m_timer->async_wait([
this] (
const auto& error) { executeEvent(error); });
127 Scheduler::executeEvent(
const boost::system::error_code& error)
133 auto guard = make_scope_exit([
this] {
134 m_isEventExecuting =
false;
137 m_isEventExecuting =
true;
141 while (!m_queue.empty()) {
142 auto head = m_queue.begin();
143 shared_ptr<EventInfo>
info = *head;
144 if (
info->expiry > now) {
149 info->isExpired =
true;
A handle for a scheduled event.
void reset() noexcept
Clear this EventId without canceling the associated event.
EventId() noexcept=default
Constructs an empty EventId.
Generic time-based event scheduler.
void cancelAllEvents()
Cancel all scheduled events.
Scheduler(boost::asio::io_context &ioCtx)
EventId schedule(time::nanoseconds after, EventCallback callback)
Schedule a one-time event after the specified delay.
static time_point now() noexcept
::boost::chrono::time_point< steady_clock > time_point
std::function< void()> EventCallback
Function to be invoked when a scheduled event expires.
::boost::chrono::nanoseconds nanoseconds