c++ 每 5 分钟调用一次函数

标签 c++ while-loop

我想每 5 分钟调用一次函数
我试过了

AutoFunction(){
    cout << "Auto Notice" << endl;
    Sleep(60000*5);
}

while(1){

    if(current->tm_hour == StartHour && current->tm_min == StartMinut && current->tm_sec == StartSec){
        CallStart();
    }

    AutoFunction();
    Sleep(1000);
}

我想每 1 秒刷新一次 while,同时 调用 AutoFunction();每 5 分钟一次,但无需等待 AutoFunction 中的 Sleep

因为我必须每 1 秒刷新一次 while(1) 以检查启动另一个函数的时间

我想这样做

while(1){

    if(current->tm_hour == StartHour && current->tm_min == StartMinut && current->tm_sec == StartSec){
        CallStart();
    }

    Sleep(1000);
}
while(1){

    AutoFunction();
    Sleep(60000*5);
}

但我认为两者不会一起工作

谢谢

最佳答案

对于我们这些不熟悉线程和 Boost 库的人来说,这可以通过一个 while 循环来完成:

void AutoFunction(){
    cout << "Auto Notice" << endl;
}

//desired number of seconds between calls to AutoFunction
int time_between_AutoFunction_calls = 5*60;

int time_of_last_AutoFunction_call = curTime() - time_between_AutoFunction_calls;

while(1){
    if (should_call_CallStart){
        CallStart();
    }

    //has enough time elapsed that we should call AutoFunction?
    if (curTime() - time_of_last_AutoFunction_call >= time_between_AutoFunction_calls){
        time_of_last_AutoFunction_call = curTime();
        AutoFunction();
    }
    Sleep(1000);
}

在此代码中,curTime 是我编写的一个函数,它以 int 形式返回 Unix 时间戳。从您选择的时间库中替换为合适的内容。

关于c++ 每 5 分钟调用一次函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13572690/

相关文章:

c++ - 具有私有(private)构造函数的类私有(private)继承的工作机制

java - try catch 选择菜单

c++ - 虽然循环条件不起作用

php - 试图弄清楚为什么这个 PHP while 循环实际上有效

C++ SSE2 内在函数

c++ - 计算 Caffe 中的前 5 错误率?

c++ - 如何使用高字节和低字节?

c++ - While 循环重复 4 次

Java for 和 while 循环没有按预期工作

c++ - Qt 插槽和信号 : no matching function in MainWindow