Search code examples
c++boosttimerasio

How to use boost asio steady timer expiry to get the execute timepoint


I want to get the time point when the boost asio steady timer fires. The documentation says "expiry Get the timer's expiry time as an absolute time". I do not understand what is the absolute time. I do not understand the result off expiry. Demo: (on wandbox)

#include <boost/asio.hpp>
#include <chrono>
#include <iostream>

int
main ()
{
  using namespace boost::asio;
  io_service io;
  auto timer = steady_timer (io);
  using namespace std::chrono_literals;
  using namespace std::chrono;
  std::cout << "before timer set" << std::endl;
  std::cout << duration_cast<seconds> (timer.expiry ().time_since_epoch ()).count () << " seconds" << std::endl;
  timer.expires_after (10s);
  std::cout << "after timer set" << std::endl;
  std::cout << duration_cast<seconds> (timer.expiry ().time_since_epoch ()).count () << " seconds" << std::endl;
  std::cout << "current time using system_clock::now ()" << std::endl;
  std::cout << duration_cast<seconds> (system_clock::now ().time_since_epoch ()).count () << " seconds" << std::endl;
  return 0;
}

Result:

before timer set
0 seconds
after timer set
21652309 seconds
current time using system_clock::now ()
1626725470 seconds

My question is how to get the time when the timer fires with boost asio steady timer?


Solution

  • The problem is that you are comparing apples to oranges. system_clock and steady_clock do not share the same epoch. In other words, they represent time from different reference points.

    The fact that you had to go through time_since_epoch() in order to compare them is a big indicator that you really shouldn't be comparing them in the first place.

    If you replace your last printout to use steady_clock::now(), the output becomes:

    before timer set
    0 seconds
    after timer set
    21656958 seconds
    current time using system_clock::now ()
    21656948 seconds
    

    With the expected difference of 10 seconds.

    My question is how to get the time when the timer fires with boost asio steady timer?

    You can get the remaining time on the timer by getting the difference between expiry() and the current time, which is simply the - operator as long as both time points are relative to the same epoch:

    cout << duration_cast<seconds>(timer.expiry() - steady_clock::now()).count() << " seconds" << std::endl;