1. //boost::posix_time::to_simple_string函数需要这两个头文件
    2. #include <boost/date_time.hpp>
    3. #include <boost/date_time/posix_time/ptime.hpp>
    4. //使用boost.chrono代替std.chrono,
    5. #define BOOST_ASIO_DISABLE_STD_CHRONO
    6. #include <boost/asio.hpp>
    7. #include <boost/asio/steady_timer.hpp>
    8. #include <boost/asio/placeholders.hpp>
    9. #include <boost/thread.hpp>
    10. class MyClass
    11. {
    12. public:
    13. MyClass() :m_work(m_io), m_timer(m_io){}
    14. public:
    15. boost::thread_group m_thgp;
    16. boost::asio::io_service m_io;
    17. boost::asio::io_service::work m_work;
    18. boost::asio::steady_timer m_timer;
    19. public:
    20. void Init()
    21. {
    22. boost::system::error_code errCode;
    23. m_thgp.create_thread(boost::bind(&boost::asio::io_service::run, boost::ref(m_io), errCode));
    24. std::cout << "Init_1, " << LocalTime() << std::endl;
    25. m_timer.expires_from_now(boost::chrono::milliseconds(4000)); //设置过期时间长度
    26. #if 0
    27. m_timer.expires_from_now(std::chrono::milliseconds(4000));
    28. #endif
    29. std::cout << "Init_2, " << LocalTime() << std::endl;
    30. m_timer.async_wait(boost::bind(&MyClass::Test, this, boost::asio::placeholders::error));//异步等待
    31. std::cout << "Init_3, " << LocalTime() << std::endl;
    32. //由Console可知, 函数立即返回了, 定时器的expires_from_now是由完成端口处理的
    33. }
    34. void Stop()
    35. {
    36. std::cout << "Stop_1, " << LocalTime() << std::endl;
    37. m_timer.cancel(); // 取消所有handler
    38. m_work.~work();
    39. m_thgp.join_all();
    40. std::cout << "Stop_2, " << LocalTime() << std::endl;
    41. }
    42. static std::string LocalTime()
    43. {
    44. return boost::posix_time::to_simple_string(boost::posix_time::microsec_clock::local_time());
    45. }
    46. void Test(const boost::system::error_code& ec)
    47. {
    48. printf("test_1, %s, ec.value=%d, ec.message=%s\n", LocalTime().c_str(), ec.value(), ec.message().c_str());
    49. if (ec) return;
    50. m_timer.expires_from_now(boost::chrono::milliseconds(4000));
    51. #if 0
    52. m_timer.expires_from_now(std::chrono::milliseconds(4000));
    53. #endif
    54. std::cout << "test_2, " << LocalTime() << std::endl;
    55. m_timer.async_wait(boost::bind(&MyClass::Test, boost::ref(*this), _1));
    56. #if 0
    57. m_timer.async_wait(boost::bind(&MyClass::Test, this, _1));
    58. m_timer.async_wait(boost::bind(&MyClass::Test, this, boost::asio::placeholders::error));
    59. #endif
    60. std::cout << "test_3, " << LocalTime() << std::endl;
    61. }
    62. };
    63. int main(int argc, char** argv)
    64. {
    65. MyClass my;
    66. my.Init();
    67. for (int i = 0; i < 30; ++i)
    68. {
    69. boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
    70. }
    71. my.Stop();
    72. std::cout << "press ENTER to exit..." << std::endl;
    73. std::cin.sync();
    74. while (getchar() != '\n') {}
    75. }