boost 定時器.

來源:互聯網
上載者:User

標籤:

  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. }  

boost 定時器.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.