1 // 2 // timer.cpp 3 // ~~~~~~~~~ 4 // 5 // Copyright (c) 2003-2021 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 <iostream> 12 #include <boost/asio.hpp> 13 #include <boost/bind/bind.hpp> 14 15 class printer 16 { 17 public: printer(boost::asio::io_context & io)18 printer(boost::asio::io_context& io) 19 : timer_(io, boost::asio::chrono::seconds(1)), 20 count_(0) 21 { 22 timer_.async_wait(boost::bind(&printer::print, this)); 23 } 24 ~printer()25 ~printer() 26 { 27 std::cout << "Final count is " << count_ << std::endl; 28 } 29 print()30 void print() 31 { 32 if (count_ < 5) 33 { 34 std::cout << count_ << std::endl; 35 ++count_; 36 37 timer_.expires_at(timer_.expiry() + boost::asio::chrono::seconds(1)); 38 timer_.async_wait(boost::bind(&printer::print, this)); 39 } 40 } 41 42 private: 43 boost::asio::steady_timer timer_; 44 int count_; 45 }; 46 main()47int main() 48 { 49 boost::asio::io_context io; 50 printer p(io); 51 io.run(); 52 53 return 0; 54 } 55