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

c++ call function every 5 minutes

本文关键字:一次 函数 分钟 调用 C++      更新时间:2023-10-16

我想每 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,同时call 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是我编造的一个函数,它将 Unix 时间戳作为 int 返回。

相关文章: