timer.cpp 990 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. void print(const boost::system::error_code& /*e*/,
  14. boost::asio::steady_timer* t, int* count)
  15. {
  16. if (*count < 5)
  17. {
  18. std::cout << *count << std::endl;
  19. ++(*count);
  20. t->expires_at(t->expiry() + boost::asio::chrono::seconds(1));
  21. t->async_wait(boost::bind(print,
  22. boost::asio::placeholders::error, t, count));
  23. }
  24. }
  25. int main()
  26. {
  27. boost::asio::io_context io;
  28. int count = 0;
  29. boost::asio::steady_timer t(io, boost::asio::chrono::seconds(1));
  30. t.async_wait(boost::bind(print,
  31. boost::asio::placeholders::error, &t, &count));
  32. io.run();
  33. std::cout << "Final count is " << count << std::endl;
  34. return 0;
  35. }