简体   繁体   English

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

[英]c++ call function every 5 minutes

I wanted to call function every 5 minutes 我想每5分钟调用一次函数
I tried 我试过了

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);
}

I want refresh the while every 1 second and at the same time call AutoFunction() ; 我想刷新while每1秒钟,并在同一时间call AutoFunction() ; every 5 minutes, but without waiting the Sleep in AutoFunction 每5分钟一次,但无需等待自动功能中的Sleep

because I have to refresh the while(1) every 1 sec to check time to start another function 因为我必须每1秒刷新一次while(1)来检查启动另一个功能的时间

I thought to do it like 我想这样做

while(1){

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

    Sleep(1000);
}
while(1){

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

but I don't think so both will working together 但我不认为两者会一起工作

Thank You 谢谢

For those of us who are unfamiliar with threads and Boost libraries, this can be done with a single while loop: 对于那些不熟悉线程和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);
}

in this code, curTime is a function I made up that returns the Unix Timestamp as an int. 在这段代码中, curTime是我curTime的一个函数,该函数以int形式返回Unix时间戳。 Substitute in whatever is appropriate from your time library of choice. 从您选择的时间库中替换任何合适的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM