Copyright 2012 -> 2013
[folly.git] / folly / TimeoutQueue.cpp
1 /*
2  * Copyright 2013 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include "folly/TimeoutQueue.h"
18 #include <algorithm>
19
20 namespace folly {
21
22 TimeoutQueue::Id TimeoutQueue::add(
23   int64_t now,
24   int64_t delay,
25   Callback callback) {
26   Id id = nextId_++;
27   timeouts_.insert({id, now + delay, -1, std::move(callback)});
28   return id;
29 }
30
31 TimeoutQueue::Id TimeoutQueue::addRepeating(
32   int64_t now,
33   int64_t interval,
34   Callback callback) {
35   Id id = nextId_++;
36   timeouts_.insert({id, now + interval, interval, std::move(callback)});
37   return id;
38 }
39
40 int64_t TimeoutQueue::nextExpiration() const {
41   return (timeouts_.empty() ? std::numeric_limits<int64_t>::max() :
42           timeouts_.get<BY_EXPIRATION>().begin()->expiration);
43 }
44
45 bool TimeoutQueue::erase(Id id) {
46   return timeouts_.get<BY_ID>().erase(id);
47 }
48
49 int64_t TimeoutQueue::runInternal(int64_t now, bool onceOnly) {
50   auto& byExpiration = timeouts_.get<BY_EXPIRATION>();
51   int64_t nextExp;
52   do {
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});
63       }
64     }
65
66     // Call callbacks
67     for (auto& event : expired) {
68       event.callback(event.id, now);
69     }
70     nextExp = nextExpiration();
71   } while (!onceOnly && nextExp <= now);
72   return nextExp;
73 }
74
75 }  // namespace folly
76