How can we create a chronicle loop in C ++?

I was wondering how we can make a loop (for example, a while loop) where the statement inside the while loop will be based on time.

To be more clear, for example, I would like to make a while loop, which I will introduce every 10 seconds.

The pseudocode will look like this:

while (10 seconds have passed) { //do Something } 

So how can one make the above pseudo code real? (Hope it was clear)

-3
source share
3 answers

This is not as simple as it seems, because although I do not think so, in some situations, calls to wait for threads may wake up earlier than requested.

To combat this, I considered it necessary to put a wait code in a loop so that when the thread wakes up, it checks whether the timeout has expired. If this is not re-starting sleep:

 using clock = std::chrono::steady_clock; // for an easier life // set the wake-up time for 10 seconds in the future auto timeout = clock::now() + std::chrono::seconds(10); for(;;) { // loop in-case of early wakeup while(clock::now() < timeout) std::this_thread::sleep_until(timeout); timeout += std::chrono::seconds(10); // reset timer // do something useful (like print the time) auto timer = std::time(0); std::cout << "loop: " << std::ctime(&timer) << '\n'; } 

Using std::this_thread::sleep_until() , the loop does not consume CPU time while it waits for 10 seconds to finish.

This can be wrapped up in a neat little class like this:

 class wait_timer { using clock = std::chrono::steady_clock; clock::duration time_to_wait; clock::time_point timeout = clock::now(); public: wait_timer(std::chrono::milliseconds ms) : time_to_wait(ms), timeout(clock::now() + ms) {} void wait() { while(clock::now() < timeout) std::this_thread::sleep_until(timeout); timeout += time_to_wait; // reset timer } }; int main() { // create it outside the loop so it doesn't // loose track of time every iteration wait_timer wt(std::chrono::seconds(2)); for(;;) { wt.wait(); // do something useful (like print the time) auto timer = std::time(0); std::cout << "loop: " << std::ctime(&timer) << '\n'; } } 
+3
source

You can use the header file <time.h> and use the internal clock to measure if 10 seconds have passed or not

 clock_t t; while (1) { // This loop runs exactly once every 10 seconds t = clock(); // Reset clock // Do something in this loop while ((double)(clock()-t)/CLOCKS_PER_SEC < 10); // Wait if 10 seconds havent passed } 

This will fail if your calculation inside the while loop takes more than 10 seconds.

0
source

You can use std::this_thread::sleep_for :

 #include <thread> #include <chrono> using namespace std; using namespace std::chrono_literals; int main() { while (1) { // some code this_thread::sleep_for(10s); } } 
0
source

All Articles