user2071938
user2071938

Reputation: 2255

boost asio async_read_some timeout

I use this code using async_read_some with timeout

        readdata=0;
        port_->async_read_some(boost::asio::buffer(vector),
                boost::bind(readCallback));


        //init async timer
        boost::asio::deadline_timer timer(io);
        timer.async_wait(boost::bind(timeoutHandler));
        timer.expires_from_now(boost::posix_time::seconds(5));

        io.reset();
        do {
            io.run_one();
        }
        while (readdata==0);

here are my callbacks

void readCallback()
{
    std::cout << "READ CALLBACK: "<<x<<std::endl;
    readdata=1;
    return;
}
void timeoutHandler()
{
   std::cout << "TIMEOUT CALLBACK: "<<x<<std::endl;
   readdata=1;
}

my Problem is that timeoutHandler is is executed instantly and not after 5 seconds

Upvotes: 3

Views: 2369

Answers (1)

Arunmu
Arunmu

Reputation: 6901

Simple mistake. You should be doing expires_from_now before calling async_wait.

#include <iostream>
#include <asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

int main() {
  asio::io_service io_s;
  asio::deadline_timer timer(io_s);
  timer.expires_from_now(boost::posix_time::seconds(5));
  timer.async_wait([](auto err_c) { std::cout << "After 5 seconds" << std::endl; } );

  io_s.reset();

  io_s.run();

  return 0;
}

Upvotes: 3

Related Questions