Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inputs to sleep_until()

Tags:

c++

sleep

As per an answer to my previous question, I am trying to use sleep_until() but cannot find a tutorial that tells me how to use it with an actual time such as 1400:00h.

There are examples like this: std::this_thread::sleep_until(system_clock::now() + seconds(10));, but I would like something that actually lets me specify a clock time. What format should this be in? I would appreciate any examples.

like image 265
sccs Avatar asked Feb 15 '23 23:02

sccs


1 Answers

To wait until a specified clock time, you need to get a time_t that represents that clock time, and then use std::chrono::system_clock::from_time_t to create a std::chrono::system_clock::time_point which you can then use with the xxx_until functions such as std::this_thread::sleep_until.

e.g.

void foo(){
    tm timeout_tm={0};
    // set timeout_tm to 14:00:01 today
    timeout_tm.tm_year = 2013 - 1900;
    timeout_tm.tm_mon = 7 - 1;
    timeout_tm.tm_mday = 10;
    timeout_tm.tm_hour = 14;
    timeout_tm.tm_min = 0;
    timeout_tm.tm_sec = 1;
    timeout_tm.tm_isdst = -1;
    time_t timeout_time_t=mktime(&timeout_tm);
    std::chrono::system_clock::time_point timeout_tp=
        std::chrono::system_clock::from_time_t(timeout_time_t);
    std::this_thread::sleep_until(timeout_tp);
}
like image 105
Anthony Williams Avatar answered Mar 02 '23 22:03

Anthony Williams