scheduler.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2013-2019 Regents of the University of California.
4  *
5  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
6  *
7  * ndn-cxx library is free software: you can redistribute it and/or modify it under the
8  * terms of the GNU Lesser General Public License as published by the Free Software
9  * Foundation, either version 3 of the License, or (at your option) any later version.
10  *
11  * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
12  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
13  * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
14  *
15  * You should have received copies of the GNU General Public License and GNU Lesser
16  * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
17  * <http://www.gnu.org/licenses/>.
18  *
19  * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
20  */
21 
23 #include "ndn-cxx/util/impl/steady-timer.hpp"
24 
25 #include <boost/scope_exit.hpp>
26 
27 namespace ndn {
28 namespace util {
29 namespace scheduler {
30 
33 class EventInfo : noncopyable
34 {
35 public:
36  EventInfo(time::nanoseconds after, EventCallback&& cb)
37  : callback(std::move(cb))
38  , expireTime(time::steady_clock::now() + after)
39  {
40  }
41 
42  time::nanoseconds
43  expiresFromNow() const
44  {
45  return std::max(expireTime - time::steady_clock::now(), 0_ns);
46  }
47 
48 public:
49  EventCallback callback;
50  Scheduler::EventQueue::const_iterator queueIt;
52  bool isExpired = false;
53 };
54 
55 EventId::EventId(Scheduler& sched, weak_ptr<EventInfo> info)
56  : CancelHandle([&sched, info] { sched.cancelImpl(info.lock()); })
57  , m_info(std::move(info))
58 {
59 }
60 
61 EventId::operator bool() const noexcept
62 {
63  auto sp = m_info.lock();
64  return sp != nullptr && !sp->isExpired;
65 }
66 
67 bool
68 EventId::operator==(const EventId& other) const noexcept
69 {
70  return (!*this && !other) ||
71  !(m_info.owner_before(other.m_info) || other.m_info.owner_before(m_info));
72 }
73 
74 void
75 EventId::reset() noexcept
76 {
77  *this = {};
78 }
79 
80 std::ostream&
81 operator<<(std::ostream& os, const EventId& eventId)
82 {
83  return os << eventId.m_info.lock();
84 }
85 
86 bool
87 Scheduler::EventQueueCompare::operator()(const shared_ptr<EventInfo>& a,
88  const shared_ptr<EventInfo>& b) const noexcept
89 {
90  return a->expireTime < b->expireTime;
91 }
92 
93 Scheduler::Scheduler(boost::asio::io_service& ioService)
94  : m_timer(make_unique<detail::SteadyTimer>(ioService))
95 {
96 }
97 
98 Scheduler::~Scheduler() = default;
99 
100 EventId
101 Scheduler::schedule(time::nanoseconds after, EventCallback callback)
102 {
103  BOOST_ASSERT(callback != nullptr);
104 
105  auto i = m_queue.insert(make_shared<EventInfo>(after, std::move(callback)));
106  (*i)->queueIt = i;
107 
108  if (!m_isEventExecuting && i == m_queue.begin()) {
109  // the new event is the first one to expire
110  this->scheduleNext();
111  }
112 
113  return EventId(*this, *i);
114 }
115 
116 void
117 Scheduler::cancelImpl(const shared_ptr<EventInfo>& info)
118 {
119  if (info == nullptr || info->isExpired) {
120  return;
121  }
122 
123  if (info->queueIt == m_queue.begin()) {
124  m_timer->cancel();
125  }
126  m_queue.erase(info->queueIt);
127 
128  if (!m_isEventExecuting) {
129  this->scheduleNext();
130  }
131 }
132 
133 void
135 {
136  m_queue.clear();
137  m_timer->cancel();
138 }
139 
140 void
141 Scheduler::scheduleNext()
142 {
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); });
146  }
147 }
148 
149 void
150 Scheduler::executeEvent(const boost::system::error_code& error)
151 {
152  if (error) { // e.g., cancelled
153  return;
154  }
155 
156  m_isEventExecuting = true;
157 
158  BOOST_SCOPE_EXIT(this_) {
159  this_->m_isEventExecuting = false;
160  this_->scheduleNext();
161  } BOOST_SCOPE_EXIT_END
162 
163  // process all expired events
164  auto now = time::steady_clock::now();
165  while (!m_queue.empty()) {
166  auto head = m_queue.begin();
167  shared_ptr<EventInfo> info = *head;
168  if (info->expireTime > now) {
169  break;
170  }
171 
172  m_queue.erase(head);
173  info->isExpired = true;
174  info->callback();
175  }
176 }
177 
178 } // namespace scheduler
179 } // namespace util
180 } // namespace ndn
void reset() noexcept
Clear this EventId without canceling.
Definition: scheduler.cpp:75
time_point TimePoint
Definition: time.hpp:225
Definition: data.cpp:26
Generic time-based scheduler.
Definition: scheduler.hpp:145
EventId() noexcept=default
Constructs an empty EventId.
static time_point now() noexcept
Definition: time.cpp:80
void cancelAllEvents()
Cancel all scheduled events.
Definition: scheduler.cpp:134
std::function< void()> EventCallback
Function to be invoked when a scheduled event expires.
Definition: scheduler.hpp:46
Scheduler(boost::asio::io_service &ioService)
Definition: scheduler.cpp:93
EventId schedule(time::nanoseconds after, EventCallback callback)
Schedule a one-time event after the specified delay.
Definition: scheduler.cpp:101
A handle of scheduled event.
Definition: scheduler.hpp:59
bool operator==(const EventId &other) const noexcept
Determine whether this and other refer to the same event, or are both empty/expired/cancelled.
Definition: scheduler.cpp:68
std::ostream & operator<<(std::ostream &os, const EventId &eventId)
Definition: scheduler.cpp:81