boost::asio::d eadline_timer renew仍然调用处理程序函数

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

本文关键字:调用 处理 程序 函数 timer asio eadline boost renew      更新时间:2023-10-16

在下面的官方提升链接中:http://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/reference/deadline_timer.html .

您可以看到我们可以在异步deadline_timer过期之前续订它。没关系,代码有效:当计时器更新时,旧的async_wait被取消了,这很好,但烦人的是当它被取消时,它仍然调用处理程序:

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);

更改活动deadline_timer的到期时间

在存在挂起的异步等待时更改计时器的到期时间会导致取消这些等待操作。若要确保与计时器关联的操作仅执行一次,请使用如下所示的内容: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.
  }
}

我想知道有没有办法在不让旧计时器调用处理程序的情况下更新和取消旧计时器,在这种情况下是 on_timeout() 函数

它可以

通过在执行实际操作之前添加一行检查(查看它是否是中止/取消事件)来修复:

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
        }
}