beshoy Mounir
beshoy Mounir

Reputation: 95

c++ call function every 5 minutes

I wanted to call function every 5 minutes
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(); every 5 minutes, but without waiting the Sleep in AutoFunction

because I have to refresh the while(1) every 1 sec to check time to start another function

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

Upvotes: 0

Views: 4257

Answers (1)

Kevin
Kevin

Reputation: 76184

For those of us who are unfamiliar with threads and Boost libraries, this can be done with a single while loop:

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. Substitute in whatever is appropriate from your time library of choice.

Upvotes: 1

Related Questions