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, const EventCallback& callback)
37  : expireTime(time::steady_clock::now() + after)
38  , isExpired(false)
39  , callback(callback)
40  {
41  }
42 
43  time::nanoseconds
44  expiresFromNow() const
45  {
46  return std::max(expireTime - time::steady_clock::now(), 0_ns);
47  }
48 
49 public:
51  bool isExpired;
52  EventCallback callback;
53  EventQueue::const_iterator queueIt;
54 };
55 
56 EventId::EventId(Scheduler& sched, weak_ptr<EventInfo> info)
57  : CancelHandle([&sched, info] { sched.cancelImpl(info.lock()); })
58  , m_info(std::move(info))
59 {
60 }
61 
62 EventId::operator bool() const noexcept
63 {
64  auto sp = m_info.lock();
65  return sp != nullptr && !sp->isExpired;
66 }
67 
68 bool
69 EventId::operator==(const EventId& other) const noexcept
70 {
71  return (!*this && !other) ||
72  !(m_info.owner_before(other.m_info) || other.m_info.owner_before(m_info));
73 }
74 
75 void
76 EventId::reset() noexcept
77 {
78  *this = {};
79 }
80 
81 std::ostream&
82 operator<<(std::ostream& os, const EventId& eventId)
83 {
84  return os << eventId.m_info.lock();
85 }
86 
87 bool
88 EventQueueCompare::operator()(const shared_ptr<EventInfo>& a, 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  , m_isEventExecuting(false)
96 {
97 }
98 
99 Scheduler::~Scheduler() = default;
100 
101 EventId
102 Scheduler::scheduleEvent(time::nanoseconds after, const EventCallback& callback)
103 {
104  BOOST_ASSERT(callback != nullptr);
105 
106  EventQueue::iterator i = m_queue.insert(make_shared<EventInfo>(after, callback));
107  (*i)->queueIt = i;
108 
109  if (!m_isEventExecuting && i == m_queue.begin()) {
110  // the new event is the first one to expire
111  this->scheduleNext();
112  }
113 
114  return EventId(*this, *i);
115 }
116 
117 void
118 Scheduler::cancelImpl(const shared_ptr<EventInfo>& info)
119 {
120  if (info == nullptr || info->isExpired) {
121  return;
122  }
123 
124  if (info->queueIt == m_queue.begin()) {
125  m_timer->cancel();
126  }
127  m_queue.erase(info->queueIt);
128 
129  if (!m_isEventExecuting) {
130  this->scheduleNext();
131  }
132 }
133 
134 void
136 {
137  m_queue.clear();
138  m_timer->cancel();
139 }
140 
141 void
142 Scheduler::scheduleNext()
143 {
144  if (!m_queue.empty()) {
145  m_timer->expires_from_now((*m_queue.begin())->expiresFromNow());
146  m_timer->async_wait([this] (const auto& error) { this->executeEvent(error); });
147  }
148 }
149 
150 void
151 Scheduler::executeEvent(const boost::system::error_code& error)
152 {
153  if (error) { // e.g., cancelled
154  return;
155  }
156 
157  m_isEventExecuting = true;
158 
159  BOOST_SCOPE_EXIT(this_) {
160  this_->m_isEventExecuting = false;
161  this_->scheduleNext();
162  } BOOST_SCOPE_EXIT_END
163 
164  // process all expired events
165  auto now = time::steady_clock::now();
166  while (!m_queue.empty()) {
167  auto head = m_queue.begin();
168  shared_ptr<EventInfo> info = *head;
169  if (info->expireTime > now) {
170  break;
171  }
172 
173  m_queue.erase(head);
174  info->isExpired = true;
175  info->callback();
176  }
177 }
178 
179 } // namespace scheduler
180 } // namespace util
181 } // namespace ndn
void reset() noexcept
Clear this EventId without canceling.
Definition: scheduler.cpp:76
time_point TimePoint
Definition: time.hpp:225
Definition: data.cpp:26
EventId() noexcept=default
Constructs an empty EventId.
static time_point now() noexcept
Definition: time.cpp:80
EventId scheduleEvent(time::nanoseconds after, const EventCallback &callback)
Schedule a one-time event after the specified delay.
Definition: scheduler.cpp:102
void cancelAllEvents()
Cancel all scheduled events.
Definition: scheduler.cpp:135
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
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:69
std::ostream & operator<<(std::ostream &os, const EventId &eventId)
Definition: scheduler.cpp:82
bool operator()(const shared_ptr< EventInfo > &a, const shared_ptr< EventInfo > &b) const noexcept
Definition: scheduler.cpp:88