/*
- * Copyright 2016 Facebook, Inc.
+ * Copyright 2017 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
*
* Note: the class uses only one thread - if you want to use more than one
- * thread use multiple FunctionScheduler objects
+ * thread, either use multiple FunctionScheduler objects, or check out
+ * ThreadedRepeatingFunctionRunner.h for a much simpler contract of
+ * "run each function periodically in its own thread".
*
* start() schedules the functions, while shutdown() terminates further
* scheduling.
StringPiece nameID = StringPiece(),
std::chrono::milliseconds startDelay = std::chrono::milliseconds(0));
+ /**
+ * Adds a new function to the FunctionScheduler to run only once.
+ */
+ void addFunctionOnce(
+ Function<void()>&& cb,
+ StringPiece nameID = StringPiece(),
+ std::chrono::milliseconds startDelay = std::chrono::milliseconds(0));
+
/**
* Add a new function to the FunctionScheduler with the time
* interval being distributed uniformly within the given interval
* Returns false if no function exists with the specified name.
*/
bool cancelFunction(StringPiece nameID);
+ bool cancelFunctionAndWait(StringPiece nameID);
/**
* All functions registered will be canceled.
*/
void cancelAllFunctions();
+ void cancelAllFunctionsAndWait();
/**
* Resets the specified function's timer.
* Stops the FunctionScheduler.
*
* It may be restarted later by calling start() again.
+ * Returns false if the scheduler was not running.
*/
- void shutdown();
+ bool shutdown();
/**
* Set the name of the worker thread.
std::string name;
std::chrono::milliseconds startDelay;
std::string intervalDescr;
+ bool runOnce;
- RepeatFunc(Function<void()>&& cback,
- IntervalDistributionFunc&& intervalFn,
- const std::string& nameID,
- const std::string& intervalDistDescription,
- std::chrono::milliseconds delay)
+ RepeatFunc(
+ Function<void()>&& cback,
+ IntervalDistributionFunc&& intervalFn,
+ const std::string& nameID,
+ const std::string& intervalDistDescription,
+ std::chrono::milliseconds delay,
+ bool once)
: cb(std::move(cback)),
intervalFunc(std::move(intervalFn)),
nextRunTime(),
name(nameID),
startDelay(delay),
- intervalDescr(intervalDistDescription) {}
+ intervalDescr(intervalDistDescription),
+ runOnce(once) {}
std::chrono::steady_clock::time_point getNextRunTime() const {
return nextRunTime;
void addFunctionToHeap(const std::unique_lock<std::mutex>& lock,
RepeatFunc&& func);
+ void addFunctionInternal(
+ Function<void()>&& cb,
+ IntervalDistributionFunc&& intervalFunc,
+ const std::string& nameID,
+ const std::string& intervalDescr,
+ std::chrono::milliseconds startDelay,
+ bool runOnce);
+
std::thread thread_;
// Mutex to protect our member variables.