Better boost asio deadline_timer example

天涯浪子 提交于 2019-12-06 01:39:12

问题


I'm after a better example of the boost::asio::deadline_timer

The examples given will always time out and call the close method. I tried calling cancel() on a timer but that causes the function passed into async_wait to be called immediately.

Whats the correct way working with timers in a async tcp client?


回答1:


You mention that calling cancel() on a timer causes the function passed to async_wait to be called immediately. This is the expected behavior but remember that you can check the error passed to the timer handler to determine if the timer was cancelled. If the timer was cancelled, operation_aborted is passed. For example:

void handleTimer(const boost::system::error_code& error) {
    if (error == boost::asio::error::operation_aborted) {
        std::cout << "Timer was canceled" << std::endl;
    }
    else if (error) {
        std::cout << "Timer error: " << error.message() << std::endl;
    }
}

Hopefully this helps. If not, what is the specific example that are you looking for?



来源:https://stackoverflow.com/questions/1918911/better-boost-asio-deadline-timer-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!