Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.
PrevUpHomeNext

Timer.1 - Using a timer synchronously

This tutorial program introduces asio by showing how to perform a blocking wait on a timer.

We start by including the necessary header files.

All of the asio classes can be used by simply including the "asio.hpp" header file.

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

All programs that use asio need to have at least one I/O execution context, such as an io_context or thread_pool object. An I/O execution context provides access to I/O functionality. We declare an object of type io_context first thing in the main function.

int main()
{
  boost::asio::io_context io;

Next we declare an object of type boost::asio::steady_timer. The core asio classes that provide I/O functionality (or as in this case timer functionality) always take a reference to an io_context as their first constructor argument. The second argument to the constructor sets the timer to expire 5 seconds from now.

  boost::asio::steady_timer t(io, boost::asio::chrono::seconds(5));

In this simple example we perform a blocking wait on the timer. That is, the call to steady_timer::wait() will not return until the timer has expired, 5 seconds after it was created (i.e. not from when the wait starts).

A timer is always in one of two states: "expired" or "not expired". If the steady_timer::wait() function is called on an expired timer, it will return immediately.

  t.wait();

Finally we print the obligatory "Hello, world!" message to show when the timer has expired.

  std::cout << "Hello, world!" << std::endl;

  return 0;
}

See the full source listing

Return to the tutorial index

Next: Timer.2 - Using a timer asynchronously


PrevUpHomeNext