2012-08-09 183 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