使用Boost基本截止时间计时器来调用类方法

Using a Boost basic deadline timer to call a class method

本文关键字:计时器 调用 类方法 时间 Boost 使用      更新时间:2023-10-16

我想绑定一个定时器回调方法在我的类。你能帮我修改一下代码吗?

tftp_connection::tftp_connection (std::string id,
                                  std::string file_name,
                                  connection_type_enum connection_type,
                                  tftp_server* server,
                                  boost::asio::io_service& io_service)
                : timer(io_service, boost::posix_time::milliseconds(5000)) {
    ...
    //timer.async_wait(callback);
    timer.async_wait(boost::bind(&tftp_connection::callback ), this);
    ...
} 
... 
void tftp_connection::callback(const boost::system::error_code& /*error*/)
{
    // TIME OUT
}

错误是:

Compilation error:
/usr/local/boost_1_55_0/boost/bind/bind.hpp:69:22: Type 'void (tftp_connection::*)(const boost::system::error_code &)' cannot be used prior to '::' because it has no members
timer.async_wait(boost::bind(&tftp_connection::callback ), this);
应该

timer.async_wait(boost::bind(&tftp_connection::callback, this));

需要将对象绑定到成员函数,因为成员函数离开它所属的对象就不能工作。

参见boost示例,使用async_wait

将成员函数用作回调