2012-04-18 104 views
1

在以下官方升级链接中: http://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/reference/deadline_timer.htmlboost :: asio :: deadline_timer续订仍然会调用处理程序函数

您可以看到我们可以在到期前更新异步deadline_timer。这很好,代码工作: 当计时器得到了更新,老async_wait被取消了这很好,但在烦扰的事情是当它取消了,但它仍然调用的处理程序:

void handler(const boost::system::error_code& error) 
{ 
    if (!error) 
    { 
    // Timer expired. 
    } 
} 

... 

// Construct a timer with an absolute expiry time. 
boost::asio::deadline_timer timer(io_service, 
    boost::posix_time::time_from_string("2005-12-07 23:59:59.000")); 

// Start an asynchronous wait. 
timer.async_wait(handler); 

更改活动deadline_timer的到期时间

在有待处理的异步等待期间更改定时器的到期时间会导致取消这些等待操作。为确保执行与计时器相关联的动作只有一次,使用这样的:使用:

void on_some_event() 
{ 
    if (my_timer.expires_from_now(seconds(5)) > 0) 
    { 
    // We managed to cancel the timer. Start new asynchronous wait. 
    my_timer.async_wait(on_timeout); 
    } 
    else 
    { 
    // Too late, timer has already expired! 
    } 
} 

void on_timeout(const boost::system::error_code& e) 
{ 
    if (e != boost::asio::error::operation_aborted) 
    { 
    // Timer was not cancelled, take necessary action. 
    } 
} 

我想知道有没有办法更新&取消旧计时器没有让老计时器调用处理,在这种情况下,on_timeout()函数

+0

AFAICT,你回答了你自己的问题的问题本身?在复制粘贴的文档中,on_timeout已经进行了适当的检查? – Rawler 2012-04-19 16:42:13

+0

是的,我没有从那里复制/粘贴代码,我写了我自己的,这就是为什么我没有发现第一个地方,但我很快就发现它并在下面添加了一个答案。但有趣的是,有人低估了这个笑声 – Gob00st 2012-04-19 16:46:42

回答

3

我愚蠢的问题,只是discoveried它可以通过添加一行检查是固定的(看它是否是一个中止/取消事件)做实际的东西之前:

void handler1(const boost::system::error_code &e) 
{ 
    if (e != boost::asio::error::operation_aborted) // here is the important part 
     { 
      //do actual stuff here if it's not a cancel/abort event 
     } 
} 
相关问题