Lv.的博客

boost 定时器.

  1. #include <iostream>  
  2. #include <boost/asio.hpp>  
  3.   
  4. int main()  
  5. {  
  6.     boost::asio::io_service io;  
  7.     boost::asio::deadline_timer timer(io, boost::posix_time::seconds(3));  
  8.   
  9.     timer.wait();  
  10.     std::cout << "Hello, world!\n";  
  11.   
  12.     return 0;  
  13. }  



 

再来个异步的:

 

[cpp] view plaincopy
 
  1. void print(const boost::system::error_code& /*e*/)  
  2. {  
  3.     std::cout << "Hello, world!\n";  
  4. }  
  5. int main()  
  6. {  
  7.     boost::asio::io_service io;  
  8.     boost::asio::deadline_timer timer(io, boost::posix_time::seconds(5));  
  9.   
  10.     timer.async_wait(&print);  
  11.     io.run();  
  12.   
  13.     return 0;  
  14. }  



 

上次演示了基本用法,但它只能发生一次.

问题是怎么定义一个重复发生的定时器(就是隔一定的时间它就会发生一次.)呢,下面的代码就是了, 关键在于回调函数中更改了延时不断的延长定时器 

 

 

 

[cpp] view plaincopy
 
    1. void print(const boost::system::error_code& e,  
    2.            boost::asio::deadline_timer* t)  
    3. {  
    4.   cout<<"ddd"<<endl;  
    5.   t->expires_at(t->expires_at()+ boost::posix_time::seconds(1));  
    6.   t->async_wait(boost::bind(print,boost::asio::placeholders::error,t));  
    7. }  
    8.   
    9. void test1()  
    10. {  
    11.    boost::asio::io_service io;  
    12.    boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));  
    13.    t.async_wait(boost::bind(print,boost::asio::placeholders::error,&t));  
    14.    io.run();  
    15. }  
    16.   
    17. int _tmain(int argc, _TCHAR* argv[])  
    18. {   
    19.   test1();  
    20.   system("pause");  
    21.   return 0;  
    22. }  
posted @ 2015-04-27 22:05  Avatarx  阅读(457)  评论(0编辑  收藏  举报