Maximum wait time of boost::asio::steady_timer

103 views Asked by At

How to set maximum waiting time of boost::asio::steady_timer in milliseconds?

  • When I set boost::asio::chrono::milliseconds::max() than timer returns immediately (why?).
  • When I set relatively short time, e.g: boost::asio::chrono::milliseconds(5000), the timer waits as expected.

I've configured the timer as written in boost::asio::steady_timer documentation:

#include <iostream>
#include <boost/asio/io_context.hpp>
#include <boost/asio/steady_timer.hpp>

void steadyTimerBlockingWait()
{
    boost::asio::io_context io;
    boost::asio::steady_timer timer(io);

    // Case (1)
    timer.expires_after(boost::asio::chrono::milliseconds::max());

    // Case (2)
    // timer.expires_after(boost::asio::chrono::milliseconds(5000));

    std::cout << "Waiting begin." << std::endl;
    timer.wait();
    std::cout << "Waiting done." << std::endl;
}

Case (1) The boost::asio::chrono::milliseconds::max().count() returns 9223372036854775807 on my computer, so I expect the timer to wait for that amount of time.
It finishes immediately without any error instead.

Case (2) Timer waits 5 seconds as expected.

I need to make the application deterministic and stable, so:

  • How to determine maximum amount of time in milliseconds when timer waits correctly?
  • Or, How do detect that given time is incorrect?
  • Or, Is there a better boost timer implementation that is secure against such misuse?
  • By the way, is it possible to set the timer to wait indefinitely (it is not the main question)?

Environment: Debian 11 (bullseye), 64-bit, Boost 1.81, gcc 10.2.1.

1

There are 1 answers

4
Alan Birtles On BEST ANSWER

expires_after(duration) is basically just expires_at(now() + duration).

With a duration of boost::asio::chrono::milliseconds::max() the calculation likely overflows to a time in the past so the timer triggers immediately.

To set a timer to never expire you should use:

timer.expires_at( decltype( timer )::time_point::max() );