-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.cpp
More file actions
65 lines (55 loc) · 1.5 KB
/
timer.cpp
File metadata and controls
65 lines (55 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//
// timer4/timer.cpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Moderniced from Claus Klein and ChatGPT
#include <fmt/format.h>
#include <boost/asio/io_context.hpp>
#include <boost/asio/steady_timer.hpp>
#include <functional>
#include <iostream>
class printer
{
static constexpr int kMaxCount{5};
public:
explicit printer(boost::asio::io_context& io) : timer_(io, boost::asio::chrono::seconds(1))
{
// cpp11: timer_.async_wait(std::bind(&printer::print, this));
timer_.async_wait([this](const boost::system::error_code& /*ec*/) { print(); });
}
~printer() { std::cout << "Final count is " << count_ << '\n'; }
void print()
{
if (count_ < kMaxCount)
{
std::cout << count_ << '\n';
++count_;
timer_.expires_at(timer_.expiry() + boost::asio::chrono::milliseconds(100));
// cpp11: timer_.async_wait(std::bind(&printer::print, this));
timer_.async_wait([this](const boost::system::error_code& /*ec*/) { print(); });
}
}
private:
boost::asio::steady_timer timer_;
int count_{};
};
auto main() -> int
{
try
{
boost::asio::io_context io;
auto p = std::make_unique< printer >(io);
io.run();
}
catch (const std::exception& e)
{
fmt::print("Error: {}\n", e.what());
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}