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>

Since this example uses timers, we need to include the appropriate Boost.Date_Time header file for manipulating times.

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

All programs that use asio need to have at least one boost::asio::io_service object. This class provides access to I/O functionality. We declare an object of this type first thing in the main function.

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

In this simple example we perform a blocking wait on the timer. That is, the call to deadline_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 deadline timer is always in one of two states: "expired" or "not expired". If the deadline_timer::wait() function is called on an expired timer, it will return immediately.

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

See the full source listing

Return to the tutorial index

Next: Timer.2 - Using a timer asynchronously


PrevUpHomeNext