简体   繁体   中英

How to make an if statement based on how much time passed?

I'm looking for a way to add an if statement that would go as the following, just unsure how to do it.

if(120 seconds have passed)
{
    // do stuff
}

alt would be (assuming x is the time passed between each check)

do
{
    // do stuff
    x = 0;
}while(x=120)

So then it would loop constantly. Could anyone show me a solution to this ?

You can use Boost.DateTime to do the job.

Here is an example describing each step:

const boost::posix_time::ptime start = boost::posix_time::microsec_clock::local_time();
// Do stuff
const boost::posix_time::ptime end = boost::posix_time::microsec_clock::local_time();
const boost::posix_time::time_duration duration = end - start;
const boost::posix_time::time_duration remaining = boost::posix_time::seconds(120) - duration;
boost::this_thread::sleep(remaining);

It can be simplified by this way:

const boost::posix_time::ptime start = boost::posix_time::microsec_clock::local_time();
// Do stuff
boost::this_thread::sleep(boost::posix_time::seconds(120) - boost::posix_time::microsec_clock::local_time() + start);

Or simplified by this way:

const boost::posix_time::ptime end = boost::posix_time::microsec_clock::local_time() + boost::posix_time::seconds(120);
// Do stuff
boost::this_thread::sleep(end - boost::posix_time::microsec_clock::local_time());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM