當您在運行的定時器上調用expires_from_now()
時,定時器被取消,並且調用新的定時器。 所以調用相關的處理程序。 很容易在處理器 中區分取消定時器和過期定時器。 然而,我想知道,如果有一種方法來區分 之間的過期和重新觸發的計時器。 在這兩種情況下,該處理程序都稱爲 ,錯誤代碼爲operation_aborted
。 或者我錯過了一些細節。如何區分從重新觸發的加速中取消deadline_timer
下面的代碼生成以下的輸出:
20120415 21:32:28079507 Main: Timer1 set to 15 s.
20120415 21:32:28079798 Main: Timer1 set to 12 s.
20120415 21:32:28079916 Handler1: Timer 1 was cancelled or retriggered.
20120415 21:32:40079860 Handler1: expired.
這表明處理器無法實現的取消處理 行動,因爲重新觸發一個計時器會調用相同的處理,從而執行相同動作。這可能不是預期的行爲。
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>
#include <iostream>
using namespace boost::posix_time;
using namespace std;
void handler1(const boost::system::error_code &ec)
{
if (ec == boost::asio::error::operation_aborted)
{
cout << microsec_clock::local_time() << " Handler1: Timer was cancelled or retriggered." << endl;
}
else
{
cout << microsec_clock::local_time() << " Handler1: Timer expired." << endl;
}
}
boost::asio::io_service io_service1;
void run1()
{
io_service1.run();
}
int main()
{
time_facet *facet = new time_facet("%Y%m%d %H:%M:%S%f");
cout.imbue(locale(cout.getloc(), facet));
boost::asio::deadline_timer timer1(io_service1, seconds(15));
timer1.async_wait(handler1);
cout << microsec_clock::local_time() << " Main: Timer1 set to 15 s." << endl;
// now actually run the timer
boost::thread thread1(run1);
timer1.expires_from_now(seconds(12));
cout << microsec_clock::local_time() << " Main: Timer1 set to 12 s." << endl;
// here the timer is running, but we need to reset the deadline
timer1.async_wait(handler1);
thread1.join(); // wait for thread1 to terminate
}
請告訴我們你想要達到的目標。什麼是更大的圖片? – 2012-04-15 19:58:52
我正試圖實現一些事件觸發的開啓延遲。我可以在不重新啓動的情況下實現基本的開啓延遲。但如果你接受變量或改變時間延遲,我將不得不重新觸發它。 – 2012-04-15 20:17:38
爲什麼不做任何事情,當你得到operation_aborted時,記住給定的處理程序並重新設置它? – 2012-04-15 20:20:35