2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <folly/Optional.h>
20 #include <folly/io/async/AsyncTimeout.h>
21 #include <folly/io/async/DelayedDestruction.h>
23 #include <boost/intrusive/list.hpp>
24 #include <glog/logging.h>
34 * Hashed Hierarchical Wheel Timer
36 * We model timers as the number of ticks until the next
37 * due event. We allow 32-bits of space to track this
38 * due interval, and break that into 4 regions of 8 bits.
39 * Each region indexes into a bucket of 256 lists.
41 * Bucket 0 represents those events that are due the soonest.
42 * Each tick causes us to look at the next list in a bucket.
43 * The 0th list in a bucket is special; it means that it is time to
44 * flush the timers from the next higher bucket and schedule them
45 * into a different bucket.
47 * This technique results in a very cheap mechanism for
48 * maintaining time and timers.
50 * Unlike the original timer wheel paper, this implementation does
51 * *not* tick constantly, and instead calculates the exact next wakeup
54 class HHWheelTimer : private folly::AsyncTimeout,
55 public folly::DelayedDestruction {
57 using UniquePtr = std::unique_ptr<HHWheelTimer, Destructor>;
58 using SharedPtr = std::shared_ptr<HHWheelTimer>;
60 template <typename... Args>
61 static UniquePtr newTimer(Args&&... args) {
62 return UniquePtr(new HHWheelTimer(std::forward<Args>(args)...));
66 * A callback to be notified when a timeout has expired.
69 : public boost::intrusive::list_base_hook<
70 boost::intrusive::link_mode<boost::intrusive::auto_unlink>> {
76 * timeoutExpired() is invoked when the timeout has expired.
78 virtual void timeoutExpired() noexcept = 0;
80 /// This callback was canceled. The default implementation is to just
81 /// proxy to `timeoutExpired` but if you care about the difference between
82 /// the timeout finishing or being canceled you can override this.
83 virtual void callbackCanceled() noexcept {
88 * Cancel the timeout, if it is running.
90 * If the timeout is not scheduled, cancelTimeout() does nothing.
92 void cancelTimeout() {
93 if (wheel_ == nullptr) {
94 // We're not scheduled, so there's nothing to do.
101 * Return true if this timeout is currently scheduled, and false otherwise.
103 bool isScheduled() const {
104 return wheel_ != nullptr;
109 * Don't override this unless you're doing a test. This is mainly here so
110 * that we can override it to simulate lag in steady_clock.
112 virtual std::chrono::steady_clock::time_point getCurTime() {
113 return std::chrono::steady_clock::now();
117 // Get the time remaining until this timeout expires
118 std::chrono::milliseconds getTimeRemaining(
119 std::chrono::steady_clock::time_point now) const {
120 if (now >= expiration_) {
121 return std::chrono::milliseconds(0);
123 return std::chrono::duration_cast<std::chrono::milliseconds>(
127 void setScheduled(HHWheelTimer* wheel,
128 std::chrono::milliseconds);
129 void cancelTimeoutImpl();
131 HHWheelTimer* wheel_{nullptr};
132 std::chrono::steady_clock::time_point expiration_{};
135 typedef boost::intrusive::list<
137 boost::intrusive::constant_time_size<false> > List;
139 std::shared_ptr<RequestContext> context_;
141 // Give HHWheelTimer direct access to our members so it can take care
142 // of scheduling/cancelling.
143 friend class HHWheelTimer;
147 * Create a new HHWheelTimer with the specified interval and the
148 * default timeout value set.
150 * Objects created using this version of constructor can be used
151 * to schedule both variable interval timeouts using
152 * scheduleTimeout(callback, timeout) method, and default
153 * interval timeouts using scheduleTimeout(callback) method.
155 static int DEFAULT_TICK_INTERVAL;
156 explicit HHWheelTimer(
157 folly::TimeoutManager* timeoutManager,
158 std::chrono::milliseconds intervalMS =
159 std::chrono::milliseconds(DEFAULT_TICK_INTERVAL),
160 AsyncTimeout::InternalEnum internal = AsyncTimeout::InternalEnum::NORMAL,
161 std::chrono::milliseconds defaultTimeoutMS =
162 std::chrono::milliseconds(-1));
165 * Cancel all outstanding timeouts
167 * @returns the number of timeouts that were cancelled.
172 * Get the tick interval for this HHWheelTimer.
174 * Returns the tick interval in milliseconds.
176 std::chrono::milliseconds getTickInterval() const {
181 * Get the default timeout interval for this HHWheelTimer.
183 * Returns the timeout interval in milliseconds.
185 std::chrono::milliseconds getDefaultTimeout() const {
186 return defaultTimeout_;
190 * Schedule the specified Callback to be invoked after the
191 * specified timeout interval.
193 * If the callback is already scheduled, this cancels the existing timeout
194 * before scheduling the new timeout.
196 void scheduleTimeout(Callback* callback,
197 std::chrono::milliseconds timeout);
198 void scheduleTimeoutImpl(Callback* callback,
199 std::chrono::milliseconds timeout);
202 * Schedule the specified Callback to be invoked after the
203 * default timeout interval.
205 * If the callback is already scheduled, this cancels the existing timeout
206 * before scheduling the new timeout.
208 * This method uses CHECK() to make sure that the default timeout was
209 * specified on the object initialization.
211 void scheduleTimeout(Callback* callback);
214 void scheduleTimeoutFn(F fn, std::chrono::milliseconds timeout) {
215 struct Wrapper : Callback {
216 Wrapper(F f) : fn_(std::move(f)) {}
217 void timeoutExpired() noexcept override {
220 } catch (std::exception const& e) {
221 LOG(ERROR) << "HHWheelTimer timeout callback threw an exception: "
224 LOG(ERROR) << "HHWheelTimer timeout callback threw a non-exception.";
230 Wrapper* w = new Wrapper(std::move(fn));
231 scheduleTimeout(w, timeout);
235 * Return the number of currently pending timeouts
237 uint64_t count() const {
241 bool isDetachable() const {
242 return !folly::AsyncTimeout::isScheduled();
245 using folly::AsyncTimeout::attachEventBase;
246 using folly::AsyncTimeout::detachEventBase;
247 using folly::AsyncTimeout::getTimeoutManager;
251 * Protected destructor.
253 * Use destroy() instead. See the comments in DelayedDestruction for more
256 ~HHWheelTimer() override;
259 // Forbidden copy constructor and assignment operator
260 HHWheelTimer(HHWheelTimer const &) = delete;
261 HHWheelTimer& operator=(HHWheelTimer const &) = delete;
263 // Methods inherited from AsyncTimeout
264 void timeoutExpired() noexcept override;
266 std::chrono::milliseconds interval_;
267 std::chrono::milliseconds defaultTimeout_;
269 static constexpr int WHEEL_BUCKETS = 4;
270 static constexpr int WHEEL_BITS = 8;
271 static constexpr unsigned int WHEEL_SIZE = (1 << WHEEL_BITS);
272 static constexpr unsigned int WHEEL_MASK = (WHEEL_SIZE - 1);
273 static constexpr uint32_t LARGEST_SLOT = 0xffffffffUL;
275 typedef Callback::List CallbackList;
276 CallbackList buckets_[WHEEL_BUCKETS][WHEEL_SIZE];
277 std::vector<uint64_t> bitmap_;
279 int64_t timeToWheelTicks(std::chrono::milliseconds t) {
280 return t.count() / interval_.count();
283 bool cascadeTimers(int bucket, int tick);
287 std::chrono::steady_clock::time_point startTime_;
289 int64_t calcNextTick();
291 void scheduleNextTimeout();
293 bool* processingCallbacksGuard_;
294 CallbackList timeouts; // Timeouts queued to run
296 std::chrono::steady_clock::time_point getCurTime() {
297 return std::chrono::steady_clock::now();