2 * Copyright 2016 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/experimental/FunctionScheduler.h>
21 #include <folly/Conv.h>
22 #include <folly/Random.h>
23 #include <folly/String.h>
24 #include <folly/ThreadName.h>
26 using std::chrono::milliseconds;
27 using std::chrono::steady_clock;
33 struct ConstIntervalFunctor {
34 const milliseconds constInterval;
36 explicit ConstIntervalFunctor(milliseconds interval)
37 : constInterval(interval) {
38 if (interval < milliseconds::zero()) {
39 throw std::invalid_argument(
41 "time interval must be non-negative");
45 milliseconds operator()() const { return constInterval; }
48 struct PoissonDistributionFunctor {
49 std::default_random_engine generator;
50 std::poisson_distribution<int> poissonRandom;
52 explicit PoissonDistributionFunctor(double meanPoissonMs)
53 : poissonRandom(meanPoissonMs) {
54 if (meanPoissonMs < 0.0) {
55 throw std::invalid_argument(
57 "Poisson mean interval must be non-negative");
61 milliseconds operator()() { return milliseconds(poissonRandom(generator)); }
64 struct UniformDistributionFunctor {
65 std::default_random_engine generator;
66 std::uniform_int_distribution<> dist;
68 UniformDistributionFunctor(milliseconds minInterval, milliseconds maxInterval)
69 : generator(Random::rand32()),
70 dist(minInterval.count(), maxInterval.count()) {
71 if (minInterval > maxInterval) {
72 throw std::invalid_argument(
74 "min time interval must be less or equal than max interval");
76 if (minInterval < milliseconds::zero()) {
77 throw std::invalid_argument(
79 "time interval must be non-negative");
83 milliseconds operator()() { return milliseconds(dist(generator)); }
86 } // anonymous namespace
88 FunctionScheduler::FunctionScheduler() {}
90 FunctionScheduler::~FunctionScheduler() {
91 // make sure to stop the thread (if running)
95 void FunctionScheduler::addFunction(Function<void()>&& cb,
96 milliseconds interval,
98 milliseconds startDelay) {
99 addFunctionGenericDistribution(
101 ConstIntervalFunctor(interval),
103 to<std::string>(interval.count(), "ms"),
107 void FunctionScheduler::addFunction(Function<void()>&& cb,
108 milliseconds interval,
109 const LatencyDistribution& latencyDistr,
111 milliseconds startDelay) {
112 if (latencyDistr.isPoisson) {
113 addFunctionGenericDistribution(
115 PoissonDistributionFunctor(latencyDistr.poissonMean),
117 to<std::string>(latencyDistr.poissonMean, "ms (Poisson mean)"),
120 addFunction(std::move(cb), interval, nameID, startDelay);
124 void FunctionScheduler::addFunctionUniformDistribution(
125 Function<void()>&& cb,
126 milliseconds minInterval,
127 milliseconds maxInterval,
129 milliseconds startDelay) {
130 addFunctionGenericDistribution(
132 UniformDistributionFunctor(minInterval, maxInterval),
135 "[", minInterval.count(), " , ", maxInterval.count(), "] ms"),
139 void FunctionScheduler::addFunctionGenericDistribution(
140 Function<void()>&& cb,
141 IntervalDistributionFunc&& intervalFunc,
142 const std::string& nameID,
143 const std::string& intervalDescr,
144 milliseconds startDelay) {
146 throw std::invalid_argument(
147 "FunctionScheduler: Scheduled function must be set");
150 throw std::invalid_argument(
151 "FunctionScheduler: interval distribution function must be set");
153 if (startDelay < milliseconds::zero()) {
154 throw std::invalid_argument(
155 "FunctionScheduler: start delay must be non-negative");
158 std::unique_lock<std::mutex> l(mutex_);
159 // check if the nameID is unique
160 for (const auto& f : functions_) {
161 if (f.isValid() && f.name == nameID) {
162 throw std::invalid_argument(
163 to<std::string>("FunctionScheduler: a function named \"",
165 "\" already exists"));
168 if (currentFunction_ && currentFunction_->name == nameID) {
169 throw std::invalid_argument(to<std::string>(
170 "FunctionScheduler: a function named \"", nameID, "\" already exists"));
177 std::move(intervalFunc),
183 bool FunctionScheduler::cancelFunction(StringPiece nameID) {
184 std::unique_lock<std::mutex> l(mutex_);
186 if (currentFunction_ && currentFunction_->name == nameID) {
187 // This function is currently being run. Clear currentFunction_
188 // The running thread will see this and won't reschedule the function.
189 currentFunction_ = nullptr;
193 for (auto it = functions_.begin(); it != functions_.end(); ++it) {
194 if (it->isValid() && it->name == nameID) {
195 cancelFunction(l, it);
202 void FunctionScheduler::cancelFunction(const std::unique_lock<std::mutex>& l,
203 FunctionHeap::iterator it) {
204 // This function should only be called with mutex_ already locked.
205 DCHECK(l.mutex() == &mutex_);
206 DCHECK(l.owns_lock());
209 // Internally gcc has an __adjust_heap() function to fill in a hole in the
210 // heap. Unfortunately it isn't part of the standard API.
212 // For now we just leave the RepeatFunc in our heap, but mark it as unused.
213 // When its nextTimeInterval comes up, the runner thread will pop it from
214 // the heap and simply throw it away.
217 // We're not running, so functions_ doesn't need to be maintained in heap
219 functions_.erase(it);
223 void FunctionScheduler::cancelAllFunctions() {
224 std::unique_lock<std::mutex> l(mutex_);
226 currentFunction_ = nullptr;
229 bool FunctionScheduler::resetFunctionTimer(StringPiece nameID) {
230 std::unique_lock<std::mutex> l(mutex_);
231 if (currentFunction_ && currentFunction_->name == nameID) {
232 RepeatFunc* funcPtrCopy = currentFunction_;
233 // This function is currently being run. Clear currentFunction_
234 // to avoid rescheduling it, and add the function again to honor the
236 currentFunction_ = nullptr;
237 addFunctionToHeap(l, std::move(*funcPtrCopy));
241 // Since __adjust_heap() isn't a part of the standard API, there's no way to
242 // fix the heap ordering if we adjust the key (nextRunTime) for the existing
243 // RepeatFunc. Instead, we just cancel it and add an identical object.
244 for (auto it = functions_.begin(); it != functions_.end(); ++it) {
245 if (it->isValid() && it->name == nameID) {
246 RepeatFunc funcCopy(std::move(*it));
247 cancelFunction(l, it);
248 addFunctionToHeap(l, std::move(funcCopy));
255 bool FunctionScheduler::start() {
256 std::unique_lock<std::mutex> l(mutex_);
263 VLOG(1) << "Starting FunctionScheduler with " << functions_.size()
265 auto now = steady_clock::now();
266 // Reset the next run time. for all functions.
267 // note: this is needed since one can shutdown() and start() again
268 for (auto& f : functions_) {
269 f.resetNextRunTime(now);
270 VLOG(1) << " - func: " << (f.name.empty() ? "(anon)" : f.name.c_str())
271 << ", period = " << f.intervalDescr
272 << ", delay = " << f.startDelay.count() << "ms";
274 std::make_heap(functions_.begin(), functions_.end(), fnCmp_);
276 thread_ = std::thread([&] { this->run(); });
280 bool FunctionScheduler::shutdown() {
282 std::lock_guard<std::mutex> g(mutex_);
288 runningCondvar_.notify_one();
294 void FunctionScheduler::run() {
295 std::unique_lock<std::mutex> lock(mutex_);
297 if (!threadName_.empty()) {
298 folly::setThreadName(threadName_);
302 // If we have nothing to run, wait until a function is added or until we
304 if (functions_.empty()) {
305 runningCondvar_.wait(lock);
309 auto now = steady_clock::now();
311 // Move the next function to run to the end of functions_
312 std::pop_heap(functions_.begin(), functions_.end(), fnCmp_);
314 // Check to see if the function was cancelled.
315 // If so, just remove it and continue around the loop.
316 if (!functions_.back().isValid()) {
317 functions_.pop_back();
321 auto sleepTime = functions_.back().getNextRunTime() - now;
322 if (sleepTime < milliseconds::zero()) {
323 // We need to run this function now
324 runOneFunction(lock, now);
326 // Re-add the function to the heap, and wait until we actually
328 std::push_heap(functions_.begin(), functions_.end(), fnCmp_);
329 runningCondvar_.wait_for(lock, sleepTime);
334 void FunctionScheduler::runOneFunction(std::unique_lock<std::mutex>& lock,
335 steady_clock::time_point now) {
336 DCHECK(lock.mutex() == &mutex_);
337 DCHECK(lock.owns_lock());
339 // The function to run will be at the end of functions_ already.
341 // Fully remove it from functions_ now.
342 // We need to release mutex_ while we invoke this function, and we need to
343 // maintain the heap property on functions_ while mutex_ is unlocked.
344 RepeatFunc func(std::move(functions_.back()));
345 functions_.pop_back();
347 VLOG(5) << func.name << "function has been canceled while waiting";
350 currentFunction_ = &func;
352 // Update the function's next run time.
354 // This allows scheduler to catch up
355 func.setNextRunTimeSteady();
357 // Note that we set nextRunTime based on the current time where we started
358 // the function call, rather than the time when the function finishes.
359 // This ensures that we call the function once every time interval, as
360 // opposed to waiting time interval seconds between calls. (These can be
361 // different if the function takes a significant amount of time to run.)
362 func.setNextRunTimeStrict(now);
365 // Release the lock while we invoke the user's function
368 // Invoke the function
370 VLOG(5) << "Now running " << func.name;
372 } catch (const std::exception& ex) {
373 LOG(ERROR) << "Error running the scheduled function <"
374 << func.name << ">: " << exceptionStr(ex);
377 // Re-acquire the lock
380 if (!currentFunction_) {
381 // The function was cancelled while we were running it.
382 // We shouldn't reschedule it;
385 // Clear currentFunction_
386 CHECK_EQ(currentFunction_, &func);
387 currentFunction_ = nullptr;
389 // Re-insert the function into our functions_ heap.
390 // We only maintain the heap property while running_ is set. (running_ may
391 // have been cleared while we were invoking the user's function.)
392 functions_.push_back(std::move(func));
394 std::push_heap(functions_.begin(), functions_.end(), fnCmp_);
398 void FunctionScheduler::addFunctionToHeap(
399 const std::unique_lock<std::mutex>& lock,
401 // This function should only be called with mutex_ already locked.
402 DCHECK(lock.mutex() == &mutex_);
403 DCHECK(lock.owns_lock());
405 functions_.emplace_back(std::move(func));
407 functions_.back().resetNextRunTime(steady_clock::now());
408 std::push_heap(functions_.begin(), functions_.end(), fnCmp_);
409 // Signal the running thread to wake up and see if it needs to change
410 // its current scheduling decision.
411 runningCondvar_.notify_one();
415 void FunctionScheduler::setThreadName(StringPiece threadName) {
416 std::unique_lock<std::mutex> l(mutex_);
417 threadName_ = threadName.str();