AbdelRahman Badr
AbdelRahman Badr

Reputation: 293

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

I need to schedule a function to execute every minute while the rest of the code is running concurrently with this function in c++.

Upvotes: 2

Views: 2931

Answers (1)

CIsForCookies
CIsForCookies

Reputation: 12807

Use threads.

Simple example:

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

What happens here is while your main is doing one thing, the foo function is executing on another thread, and the main is waiting for it to end (th.join() waits for th to end).

Notice, I'm assuming your foo function execution is very short, and that's why I set the sleepfor() argument to 60 sec. You should check if it is so. You can use std::clock() to measure the time elapsed and use smaller arguments for the sleepfor()

Upvotes: 3

Related Questions