Boost logo

Boost Users :

Subject: [Boost-users] Asio timer - how to restart it?
From: Peleg (pelegsh_at_[hidden])
Date: 2008-10-23 06:35:29

I'm writing an Asio based serial port communication application.
I've tried to use Asio timer as receive time out timer.
The implementation consist of restarting the timer each time the receive
event is called,
, so it'll trigger only after time out duration with no receive event.
The problem is that when I try to restart the timer, using
expires_from_now(), the timer immediately

I've written a simplified code that demonstrate this problem:

#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace std;
using namespace boost::posix_time;

void delay(int sec)
        boost::posix_time::ptime expire_time = second_clock::local_time() +
        while(second_clock::local_time() < expire_time)

void on_time_out(const boost::system::error_code& )
        cout << second_clock::local_time() <<" Time out!" << endl;

int main()
        boost::asio::io_service io;
        cout << second_clock::local_time() << " Starting timer" << endl;
        boost::asio::deadline_timer timer(io, boost::posix_time::seconds(5));
        boost::thread thread(boost::bind(&boost::asio::io_service::run, &io));

        cout << second_clock::local_time() << " Restarting timer" << endl;

        return 0;

This code results the following output:

2008-Oct-23 13:22:59 Starting timer
2008-Oct-23 13:23:02 Restarting timer
2008-Oct-23 13:23:02 Time out!

As you can see to on_time_out() is called immediately after
expires_from_now() call,
with no actual time out.

How do I restart to timer in the right way?


View this message in context:
Sent from the Boost - Users mailing list archive at

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at