Is there a simple way to install a regularly occurring timer function with C++/stdlib? I would like to get rid of the loop:
using namespace std::chrono; // literal suffixes
auto tNext = steady_clock::now();
while (<condition>) {
std::this_thread::sleep_until(tNext);
tNext = tNext + 100ms;
...
That function will run in its own thread.
I'm guessing what you want is this
Assuming performance is not critical and the timer is not often updated, the following should provide ample functionality.
timer
calls previously pushedcallback
s periodically, and whenpredicate
evaluates tofalse
, deletes thecallback
from thetimer
. Thetimer
object has its own lifetime and its worker thread will only live as long as it is alive.The reason you would want to have multiple
job
s in a singletimer
is so that they would be called together, using only one thread and be in sync with each other.Don't worry about the
mutex
unless you are planning to update the timer >10,000 times a second, have a period of <1ms or have very time-consumingcallback
s.