views:

806

answers:

1

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?

+4  A: 

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?

Yukiko