Search code examples
c++c++-chrono

Run function every 5s inside loop running every second


I need to run my function MyFunc() every five seconds using the parameters in the code (i.e. minimum code changes).

There are two parameters in the code: ts and std::chrono::system_clock::now()

What do I write in condition so that I can run my function at the interval?

auto ts = std::chrono::system_clock::now() + std::chrono::seconds(1);

do {
    // 1s timer
    if ( ts <= std::chrono::system_clock::now()) {

        // ... doing some work

        // here I need to start MyFunc() every 5s
        if (condition) {
            MyFunc();
        }

        ts += std::chrono::seconds(1);
    }

} while (isWork);

Solution

  • The way in my mind is to check whether the time passed is greater than 5 seconds. You could do something similar to this, where there is a separate variable to keep track of 5 seconds after the last time that the function was run:

    auto ts = std::chrono::system_clock::now() + std::chrono::seconds(1);
    auto fiveseconds = std::chrono::system_clock::now() + std::chrono::seconds(5);
    
    do {
        // 1s timer
        if ( ts <= std::chrono::system_clock::now()) {
    
            // ... doing some work
    
            // here I need to start MyFunc() every 5s
            if (fiveseconds <= std::chrono::system_clock::now()) {
                MyFunc();
                fiveseconds = std::chrono::system_clock::now() + std::chrono::seconds(5);
            }
    
            ts += std::chrono::seconds(1);
        }
    
    } while (isWork);
    

    Note that this may not run it exactly every five seconds, just about when it runs the once-a-second loop, and then checks if it has been over five seconds.