timer.cpp 1023 B

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