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


Hello,
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
triggers.

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() +
boost::posix_time::seconds(sec);
        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));
        timer.async_wait(on_time_out);

        delay(3);
        cout << second_clock::local_time() << " Restarting timer" << endl;
        timer.expires_from_now(boost::posix_time::seconds(5));

        delay(12);
        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?

Thanks,
Peleg

-- 
View this message in context: http://www.nabble.com/Asio-timer---how-to-restart-it--tp20128401p20128401.html
Sent from the Boost - Users mailing list archive at Nabble.com.

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net