Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Boost ASIO simple periodic timer?

I want a very simple periodic timer to call my code every 50ms. I could make a thread that sleeps for 50ms all the time (but that's a pain)... I could start looking into Linux API's for making timers (but it's not portable)...

I'd like to use boost.. I'm just not sure it's possible. Does boost provide this functionality?

like image 486
Scott Avatar asked Nov 24 '10 13:11

Scott


2 Answers

A very simple, but fully functional example:

#include <iostream> #include <boost/asio.hpp>  boost::asio::io_service io_service; boost::posix_time::seconds interval(1);  // 1 second boost::asio::deadline_timer timer(io_service, interval);  void tick(const boost::system::error_code& /*e*/) {      std::cout << "tick" << std::endl;      // Reschedule the timer for 1 second in the future:     timer.expires_at(timer.expires_at() + interval);     // Posts the timer event     timer.async_wait(tick); }  int main(void) {      // Schedule the timer for the first time:     timer.async_wait(tick);     // Enter IO loop. The timer will fire for the first time 1 second from now:     io_service.run();     return 0; } 

Notice that it is very important to call expires_at() to set a new expiration time, otherwise the timer will fire immediately because it's current due time already expired.

like image 125
Lucio Paiva Avatar answered Sep 19 '22 05:09

Lucio Paiva


The second example on Boosts Asio tutorials explains it.
You can find it here.

After that, check the 3rd example to see how you can call it again with a periodic time intervall

like image 37
default Avatar answered Sep 20 '22 05:09

default