Liapo1
Liapo1

Reputation: 21

How to use a c++ timer so that the functions i want to execute executes when a certain time has come?

Basically my goal is to call a function when a certain time has come, i have tried something like this but it doesnt work:

#include <ctime>
#include <chrono> 
#include <iostream>


class Timer
{
private:

    using clock_type = std::chrono::steady_clock;
    using second_type = std::chrono::duration<double, std::ratio<1> >;

    std::chrono::time_point<clock_type> m_beg{ clock_type::now() };

public:

    void reset()
    {
        m_beg = clock_type::now();
    }

    double elapsed() const
    {
        return std::chrono::duration_cast<second_type>(clock_type::now() - m_beg).count();
    }
};

int main()
{
    
    Timer t;
    while (true)
    {
        double time{ 1.00 };
        std::cout << "Time taken: " << t.elapsed() << " seconds\n";
        if (t.elapsed() == time)
        {
            //call some random func
        }
    }
    return 0;
}

Any ideas on why this doesnt work and are there any better ways to do this?

for example my goal is to execute func1 at time 13.4 execute func2 at time 16.5 and so on..

Os: Win10 64bit

Upvotes: 0

Views: 2050

Answers (2)

catnip
catnip

Reputation: 25388

Since you're on Windows, so long as your program has a message loop and is actively pumping messages then you can simply do:

SetTimer (NULL, 0, time_to_wait_for, MyTimerProc);

Where MyTimerProc would look something like this:

void CALLBACK MyTimerProc (HWND hWnd, UINT uMsg, UINT_PTR timer_id, DWORD elapsed)
{
    KillTimer (hWnd, timer_id);
    // ... do whatever it is you wanted to do after time_to_wait_for
}

There's a link to the documentation in Vlad's answer. time_to_wait_for is specified in milliseconds.

Upvotes: 1

Vlad Feinstein
Vlad Feinstein

Reputation: 11311

You can do this:

std::thread timer([]() {
  std::this_thread::sleep_until(<your target time>);
  // call your "random" function
});

You can also use Win32 API: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-settimer, but I don't see how it will be easier...

Upvotes: 1

Related Questions