2012-08-09 94 views
2

我想在最後一個異步事件發生後n秒後延遲一次特定操作。因此,如果連續事件在n秒內出現,則具體操作被延遲(deadline_timer重新啓動)。使用boost的延遲操作:: deadline_timer

我修改了從boost deadline_timer issue開始的定時器類,爲了簡單起見,事件是同步生成的。運行代碼,我希望是這樣的:

1 second(s) 
2 second(s) 
3 second(s) 
4 second(s) 
5 second(s) 
action  <--- it should appear after 10 seconds after the last event 

,但我得到

1 second(s) 
2 second(s) 
action 
3 second(s) 
action 
4 second(s) 
action 
5 second(s) 
action 
action 

爲什麼會出現這種情況?如何解決這個問題?

#include <boost/asio.hpp> 
#include <boost/thread.hpp> 
#include <iostream> 

class DelayedAction 
{ 
public: 
    DelayedAction():   
     work(service), 
     thread(boost::bind(&DelayedAction::run, this)), 
     timer(service) 
    {} 

    ~DelayedAction() 
    { 
     thread.join(); 
    } 

    void startAfter(const size_t delay) 
    { 
     timer.cancel(); 
     timer.expires_from_now(boost::posix_time::seconds(delay)); 
     timer.async_wait(boost::bind(&DelayedAction::action, this)); 
    } 

private: 
    void run() 
    { 
     service.run(); 
    } 

    void action() 
    { 
     std::cout << "action" << std::endl; 
    } 

    boost::asio::io_service   service; 
    boost::asio::io_service::work work; 
    boost::thread     thread; 
    boost::asio::deadline_timer  timer; 
}; 

int main() 
{ 
    DelayedAction d; 
    for(int i = 1; i < 6; ++i) 
    { 
     Sleep(1000); 
     std::cout << i << " second(s)\n"; 
     d.startAfter(10); 
    } 
} 

PS寫這個,我想真正的問題是boost :: deadline_timer一旦啓動就可以重啓。

回答

3

當您致電expires_from_now()時,它重置計時器,並立即調用處理程序,錯誤代碼爲boost::asio::error::operation_aborted

如果您在處理程序中處理錯誤代碼大小寫,那麼您可以按預期工作。

void startAfter(const size_t delay) 
{ 
    // no need to explicitly cancel 
    // timer.cancel(); 
    timer.expires_from_now(boost::posix_time::seconds(delay)); 
    timer.async_wait(boost::bind(&DelayedAction::action, this, boost::asio::placeholders::error)); 
} 

// ... 

void action(const boost::system::error_code& e) 
{ 
    if(e != boost::asio::error::operation_aborted) 
     std::cout << "action" << std::endl; 
} 

此文檔中討論: http://www.boost.org/doc/libs/1_47_0/doc/html/boost_asio/reference/deadline_timer.html

具體請參見標題爲:更改活動deadline_timer的到期時間

+0

謝謝,問題解決了!在我看來,這種行爲:取消行爲的結果是行爲的執行,是位計數器直觀的。 – Flaviu 2012-08-10 07:27:44

+0

@FlaviuC如果解決了您的問題,請點擊綠色複選標記以接受答案。 – 2012-08-10 15:24:20