1//
2// deferred_7.cpp
3// ~~~~~~~~~~~~~~
4//
5// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
6//
7// Distributed under the Boost Software License, Version 1.0. (See accompanying
8// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9//
10
11#include <boost/asio.hpp>
12#include <iostream>
13
14using boost::asio::append;
15using boost::asio::deferred;
16
17template <typename CompletionToken>
18auto async_wait_twice(boost::asio::steady_timer& timer, CompletionToken&& token)
19{
20 return deferred.values(args: &timer)
21 | deferred(
22 [](boost::asio::steady_timer* timer)
23 {
24 timer->expires_after(expiry_time: std::chrono::seconds(1));
25 return timer->async_wait(token: append(completion_token: deferred, values&: timer));
26 }
27 )
28 | deferred(
29 [](boost::system::error_code ec, boost::asio::steady_timer* timer)
30 {
31 std::cout << "first timer wait finished: " << ec.message() << "\n";
32 timer->expires_after(expiry_time: std::chrono::seconds(1));
33 return deferred.when(b: !ec)
34 .then(on_true: timer->async_wait(token: deferred))
35 .otherwise(on_false: deferred.values(args&: ec));
36 }
37 )
38 | deferred(
39 [](boost::system::error_code ec)
40 {
41 std::cout << "second timer wait finished: " << ec.message() << "\n";
42 return deferred.when(b: !ec)
43 .then(on_true: deferred.values(args: 42))
44 .otherwise(on_false: deferred.values(args: 0));
45 }
46 )
47 | std::forward<CompletionToken>(token);
48}
49
50int main()
51{
52 boost::asio::io_context ctx;
53
54 boost::asio::steady_timer timer(ctx);
55 timer.expires_after(expiry_time: std::chrono::seconds(1));
56
57 async_wait_twice(
58 timer,
59 token: [](int result)
60 {
61 std::cout << "result is " << result << "\n";
62 }
63 );
64
65 // Uncomment the following line to trigger an error in async_wait_twice.
66 //timer.cancel();
67
68 ctx.run();
69
70 return 0;
71}
72

source code of boost/libs/asio/example/cpp14/deferred/deferred_7.cpp