There is no built-in in C ++ setInterval
. you can simulate this function using an asynchronous function:
template <class F, class... Args>
void setInterval(std::atomic_bool& cancelToken,size_t interval,F&& f, Args&&... args){
cancelToken.store(true);
auto cb = std::bind(std::forward<F>(f),std::forward<Args>(args)...);
std::async(std::launch::async,[=,&cancelToken]()mutable{
while (cancelToken.load()){
cb();
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
}
});
}
use cancelToken
to cancel interval with
cancelToken.store(false);
notice, however, that this mechanism creates a new thread for the task. It cannot be used for many interval functions. in this case, I would use the already written thread pool with some kind of mechanism for measuring time.
Edit: example use:
int main(int argc, const char * argv[]) {
std::atomic_bool b;
setInterval(b, 1000, printf, "hi there\n");
getchar();
}
source
share