c++ - boost::asio::deadline_timer cancel() 方法未调用计时器处理程序

标签 c++ boost https timer boost-asio

boost 1.69

嗨。我正在尝试创建一个类来执行 https 请求,但也有错误检查超时。

我正在为 https 使用 boost beast 函数(工作正常)并且我正在使用 deadline_timer 类来设置计时器

我将 https 请求和计时器设置为在相同的 IO_context 上运行。这个想法是,如果发生超时,我想抛出错误并停止执行 IO 上下文,或者如果 https 正常工作,我想停止计时器。

我正在尝试使用 cancel() 方法来停止计时器并根据文档状态调用超时句柄

This function forces the completion of any pending asynchronous wait operations against the timer. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code

但是定时器处理程序永远不会被调用。如何在取消定时器时调用定时器处理程序?

这是一些代码:

    /* Set up timeout timer and start it */
    boost::asio::deadline_timer timer{query->ioc,boost::posix_time::seconds(TIMEOUT_HTTPS)};
    timer.async_wait(std::bind(&HttpsCom::on_timeout, this, std::placeholders::_1, query));

    // Look up the domain name
    std::cout << "Making the request..." << std::endl;
    tcp::resolver resolver{query->ioc};
    resolver.async_resolve(host, port, std::bind(&HttpsCom::on_resolve,this,std::placeholders::_1,std::placeholders::_2, query));

    query->ioc.run();

 if (latestError == HTTPS_SUCCESS){
      std::size_t test = timer.cancel();
      std::cout << test << std::endl; // Timer gets cancel as test = 1 
}

这是我的定时器处理程序

void HttpsCom::on_timeout(const boost::system::error_code& ec, std::shared_ptr<HTTPSQueryStruct_t> query){
  std::cout << "Timeout" << std::endl;
  }

这是我的关闭处理程序(HTTPS 成功)

void HttpsCom::on_shutdown(boost::system::error_code ec, std::shared_ptr<HTTPSQueryStruct_t> query){
  std::cout << "on_shutdown()" << std::endl;

  // boost::ignore_unused(ec);
  std::cerr << "on_shutdown" << ": " << ec.message() << std::endl;    

  /* If we get here the connection was closed gracefully */
  setLatestErrorCode(HTTPS_SUCCESS);
  query->ioc.stop();
}

最佳答案

我发现了问题。似乎停止 ioc 只是删除或以某种方式忘记了排队的处理程序。因此,当在停止 ioc 后调用 timer.cancel() 函数时,您不会去任何地方,因为它已经忘记了处理程序。

关于c++ - boost::asio::deadline_timer cancel() 方法未调用计时器处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57929338/

相关文章:

c++ - boost any library的典型用法是什么?

c++ - BOOST ASIO - 如何编写控制台服务器

apache - 使用 SSL 时 VirtualHost 配置(重写)不起作用

c++ - 在 C++ 中使用抽象基类和模板进行重构

c++ - 如何通过 qmake DEFINES 添加字符串值宏?

c++ - boost char_ptr_holder 实例化

apache - ACM 上的通配符 SSL 但不适用于子域

c++ - 使用 gtkmm 编译 Hello world 程序的问题

C++ 类 - 如何从函数返回自定义类型的 vector ?

ssl - Traefik TLS 证书导致 curl 出现 "unknown CA"错误,适用于浏览器