2 * Copyright 2012 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.
17 #include "folly/TimeoutQueue.h"
22 TimeoutQueue::Id TimeoutQueue::add(
27 timeouts_.insert({id, now + delay, -1, std::move(callback)});
31 TimeoutQueue::Id TimeoutQueue::addRepeating(
36 timeouts_.insert({id, now + interval, interval, std::move(callback)});
40 int64_t TimeoutQueue::nextExpiration() const {
41 return (timeouts_.empty() ? std::numeric_limits<int64_t>::max() :
42 timeouts_.get<BY_EXPIRATION>().begin()->expiration);
45 bool TimeoutQueue::erase(Id id) {
46 return timeouts_.get<BY_ID>().erase(id);
49 int64_t TimeoutQueue::runInternal(int64_t now, bool onceOnly) {
50 auto& byExpiration = timeouts_.get<BY_EXPIRATION>();
53 auto end = byExpiration.upper_bound(now);
54 std::vector<Event> expired;
55 std::move(byExpiration.begin(), end, std::back_inserter(expired));
56 byExpiration.erase(byExpiration.begin(), end);
57 for (auto& event : expired) {
58 // Reinsert if repeating, do this before executing callbacks
59 // so the callbacks have a chance to call erase
60 if (event.repeatInterval >= 0) {
61 timeouts_.insert({event.id, now + event.repeatInterval,
62 event.repeatInterval, event.callback});
67 for (auto& event : expired) {
68 event.callback(event.id, now);
70 nextExp = nextExpiration();
71 } while (!onceOnly && nextExp <= now);