2012-04-18 109 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 
     } 
} 
相關問題