如何在其他代码运行时每分钟执行一个函数

How to execute a function every minute while the rest of code is running

本文关键字:函数 一个 执行 每分钟 其他 代码 运行时      更新时间:2023-10-16

我需要安排一个函数每分钟执行一次,而其余的代码在c++中与该函数并发运行。

使用线程

简单的例子:

void foo(){
  while(CONDITION){
    // do something
    std::this_thread::sleep_for(60s); // this function holds the foo execution for 60 sec
    // should add an exit condition or this function will non stop
  }
}
int main(){
    std::thread th(foo);
    // do somthing else
    th.join();
}

这里发生的事情是,当您的main正在做一件事时,foo函数正在另一个线程上执行,并且main正在等待它结束(the .join()等待th结束)。

注意,我假设你的foo函数执行时间很短,这就是为什么我将sleepfor()参数设置为60秒。你应该检查它是否如此。您可以使用std::clock()来度量经过的时间,并为sleepfor()

使用较小的参数
相关文章: