2 * Copyright 2015 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 #ifndef FOLLY_EXPERIMENTAL_FUNCTION_SCHEDULER_H_
18 #define FOLLY_EXPERIMENTAL_FUNCTION_SCHEDULER_H_
20 #include <folly/Range.h>
22 #include <condition_variable>
30 * Schedules any number of functions to run at various intervals. E.g.,
32 * FunctionScheduler fs;
34 * fs.addFunction([&] { LOG(INFO) << "tick..."; }, seconds(1), "ticker");
35 * fs.addFunction(std::bind(&TestClass::doStuff, this), minutes(5), "stuff");
38 * fs.cancelFunction("ticker");
39 * fs.addFunction([&] { LOG(INFO) << "tock..."; }, minutes(3), "tocker");
44 * Note: the class uses only one thread - if you want to use more than one
45 * thread use multiple FunctionScheduler objects
47 * start() schedules the functions, while shutdown() terminates further
50 class FunctionScheduler {
56 * By default steady is false, meaning schedules may lag behind overtime.
57 * This could be due to long running tasks or time drift because of randomness
58 * in thread wakeup time.
59 * By setting steady to true, FunctionScheduler will attempt to catch up.
60 * i.e. more like a cronjob
62 * NOTE: it's only safe to set this before calling start()
64 void setSteady(bool steady) { steady_ = steady; }
67 * Parameters to control the function interval.
69 * If isPoisson is true, then use std::poisson_distribution to pick the
70 * interval between each invocation of the function.
72 * If isPoisson os false, then always use fixed the interval specified to
75 struct LatencyDistribution {
79 LatencyDistribution(bool poisson, double mean)
86 * Adds a new function to the FunctionScheduler.
88 * Functions will not be run until start() is called. When start() is
89 * called, each function will be run after its specified startDelay.
90 * Functions may also be added after start() has been called, in which case
91 * startDelay is still honored.
93 * Throws an exception on error. In particular, each function must have a
94 * unique name--two functions cannot be added with the same name.
96 void addFunction(const std::function<void()>& cb,
97 std::chrono::milliseconds interval,
98 StringPiece nameID = StringPiece(),
99 std::chrono::milliseconds startDelay =
100 std::chrono::milliseconds(0));
103 * Add a new function to the FunctionScheduler with a specified
104 * LatencyDistribution
107 const std::function<void()>& cb,
108 std::chrono::milliseconds interval,
109 const LatencyDistribution& latencyDistr,
110 StringPiece nameID = StringPiece(),
111 std::chrono::milliseconds startDelay = std::chrono::milliseconds(0));
114 * Add a new function to the FunctionScheduler with the time
115 * interval being distributed uniformly within the given interval
116 * [minInterval, maxInterval].
118 void addFunctionUniformDistribution(const std::function<void()>& cb,
119 std::chrono::milliseconds minInterval,
120 std::chrono::milliseconds maxInterval,
122 std::chrono::milliseconds startDelay);
125 * A type alias for function that is called to determine the time
126 * interval for the next scheduled run.
128 using IntervalDistributionFunc = std::function<std::chrono::milliseconds()>;
131 * Add a new function to the FunctionScheduler. The scheduling interval
132 * is determined by the interval distribution functor, which is called
133 * every time the next function execution is scheduled. This allows
134 * for supporting custom interval distribution algorithms in addition
135 * to built in constant interval; and Poisson and jitter distributions
136 * (@see FunctionScheduler::addFunction and
137 * @see FunctionScheduler::addFunctionJitterInterval).
139 void addFunctionGenericDistribution(
140 const std::function<void()>& cb,
141 const IntervalDistributionFunc& intervalFunc,
142 const std::string& nameID,
143 const std::string& intervalDescr,
144 std::chrono::milliseconds startDelay);
147 * Cancels the function with the specified name, so it will no longer be run.
149 * Returns false if no function exists with the specified name.
151 bool cancelFunction(StringPiece nameID);
154 * All functions registered will be canceled.
156 void cancelAllFunctions();
159 * Starts the scheduler.
161 * Returns false if the scheduler was already running.
166 * Stops the FunctionScheduler.
168 * It may be restarted later by calling start() again.
173 * Set the name of the worker thread.
175 void setThreadName(StringPiece threadName);
179 std::function<void()> cb;
180 IntervalDistributionFunc intervalFunc;
181 std::chrono::steady_clock::time_point nextRunTime;
183 std::chrono::milliseconds startDelay;
184 std::string intervalDescr;
186 RepeatFunc(const std::function<void()>& cback,
187 const IntervalDistributionFunc& intervalFn,
188 const std::string& nameID,
189 const std::string& intervalDistDescription,
190 std::chrono::milliseconds delay)
192 intervalFunc(intervalFn),
196 intervalDescr(intervalDistDescription) {}
198 std::chrono::steady_clock::time_point getNextRunTime() const {
201 void setNextRunTimeStrict(std::chrono::steady_clock::time_point curTime) {
202 nextRunTime = curTime + intervalFunc();
204 void setNextRunTimeSteady() { nextRunTime += intervalFunc(); }
205 void resetNextRunTime(std::chrono::steady_clock::time_point curTime) {
206 nextRunTime = curTime + startDelay;
209 // Simply reset cb to an empty function.
210 cb = std::function<void()>();
212 bool isValid() const { return bool(cb); }
215 struct RunTimeOrder {
216 bool operator()(const RepeatFunc& f1, const RepeatFunc& f2) const {
217 return f1.getNextRunTime() > f2.getNextRunTime();
221 typedef std::vector<RepeatFunc> FunctionHeap;
224 void runOneFunction(std::unique_lock<std::mutex>& lock,
225 std::chrono::steady_clock::time_point now);
226 void cancelFunction(const std::unique_lock<std::mutex>& lock,
227 FunctionHeap::iterator it);
231 // Mutex to protect our member variables.
233 bool running_{false};
235 // The functions to run.
236 // This is a heap, ordered by next run time.
237 FunctionHeap functions_;
240 // The function currently being invoked by the running thread.
241 // This is null when the running thread is idle
242 RepeatFunc* currentFunction_{nullptr};
244 // Condition variable that is signalled whenever a new function is added
245 // or when the FunctionScheduler is stopped.
246 std::condition_variable runningCondvar_;
248 std::string threadName_;