Magnusmanu
Magnusmanu

Reputation: 61

C++ simple timer/tick function

as the title says I want to create a simple timer/tick function that counts for example 5 minutes so that i can call an other function then the timer starts again an so on but without using sleep or a clock function. So is there any function or method so that it counts for example in seconds up or down? Thanks for your help.

Upvotes: 5

Views: 10171

Answers (1)

quantdev
quantdev

Reputation: 23793

Although you said that you wanted to avoid "clock function", I don't see how to count 5 minutes without a clock. Here is a very basic, but portable, timer.

Result : the foo() method is called every 5 minutes.


#include <thread>
#include <iostream>

void foo()
{
    std::cout << "Hello !\n";   
}

int main()
{
    std::thread([&]
    {
        while(true)
        {
            // Wait 5 minutes
            std::this_thread::sleep_for(std::chrono::minutes(5));
            // Call our method
            foo();
        }
    }).detach();

    // Execution continues ...
    std::cin.get();
}

Notes :

  • I passed a lambda to the thread but any callable would do.
  • std::chrono is full of cool stuff to manipulate date and times, you can easily tune your timer with it.

Upvotes: 4

Related Questions