RoundPi
RoundPi

Reputation: 5947

boost::asio::deadline_timer renew still calls the handler function

In the official boost link below: http://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/reference/deadline_timer.html .

You can see we can renew a async deadline_timer before it expires. That's fine, the code works: when timer got renewed, the old async_wait got cancelled that's fine but the annoy thing is when it's cancelled, it still called the handler :

void handler(const boost::system::error_code& error)
{
  if (!error)
  {
    // Timer expired.
  }
}

...

// Construct a timer with an absolute expiry time.
boost::asio::deadline_timer timer(io_service,
    boost::posix_time::time_from_string("2005-12-07 23:59:59.000"));

// Start an asynchronous wait.
timer.async_wait(handler);

Changing an active deadline_timer's expiry time

Changing the expiry time of a timer while there are pending asynchronous waits causes those wait operations to be cancelled. To ensure that the action associated with the timer is performed only once, use something like this: used:

void on_some_event()
{
  if (my_timer.expires_from_now(seconds(5)) > 0)
  {
    // We managed to cancel the timer. Start new asynchronous wait.
    my_timer.async_wait(on_timeout);
  }
  else
  {
    // Too late, timer has already expired!
  }
}

void on_timeout(const boost::system::error_code& e)
{
  if (e != boost::asio::error::operation_aborted)
  {
    // Timer was not cancelled, take necessary action.
  }
}

I am wondering is there way to renew & cancel the old timer without letting the old timer calling the handler, in this case the on_timeout() function?

Upvotes: 1

Views: 2690

Answers (1)

RoundPi
RoundPi

Reputation: 5947

It can be fixed by adding one line check (see if it's an abort/cancel event) before doing actual stuff:

void handler1(const boost::system::error_code &e)
{
    if (e != boost::asio::error::operation_aborted) // here is the important part
        {
            //do actual stuff here if it's not a cancel/abort event
        }
}

Upvotes: 3

Related Questions