When I try to get (not set!) The current expiration time using boost expires_from_now (), it seems to actually cancel the timer, but it actually works as expected, but finally does not call the handler.
this assumption is false. When you create your deadline_timer
m_pTimer = new boost::asio::deadline_timer(io_service1); m_pTimer->async_wait(handler1);
you said that it expires immediately. Then when you start your io_service
m_pThread = new boost::thread(&Mytimer::runTimerThread, this);
you subsequently call
m_pTimer->expires_from_now(boost::posix_time::seconds(10));
which, in accordance with the documentation, describes that this will cancel any outstanding handlers, a selection is added - mine.
This function sets the expiration time. Waiting for asynchronous wait operations will be canceled . The handler for each canceled operation will be called with the error boost::asio::error::operation_aborted code.
To solve this problem, change the Mytimer::startTimer() method as follows
--- timer4.cc.orig 2012-04-13 11:18:47.000000000 -0500 +++ timer4.cc 2012-04-13 11:16:54.000000000 -0500 @@ -1,4 +1,3 @@ - #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> @@ -39,7 +38,6 @@ m_pThread(NULL) { m_pTimer = new boost::asio::deadline_timer(io_service1); - m_pTimer->async_wait(handler1); } void Mytimer::runTimerThread() @@ -49,8 +47,9 @@ void Mytimer::startTimer() { - m_pThread = new boost::thread(&Mytimer::runTimerThread, this); m_pTimer->expires_from_now(boost::posix_time::seconds(10)); + m_pTimer->async_wait(handler1); + m_pThread = new boost::thread(&Mytimer::runTimerThread, this); } bool Mytimer::isRunning()
leading to expected behavior
mbp:stackoverflow samm$ ./a.out 20120413 11:17:22922529 before timer construction 20120413 11:17:22923155 before startTimer() 20120413 11:17:22923530 IsRunning: 1 20120413 11:17:23924702 IsRunning: 1 20120413 11:17:24925971 IsRunning: 1 20120413 11:17:25927320 IsRunning: 1 20120413 11:17:26928715 IsRunning: 1 20120413 11:17:27929969 IsRunning: 1 20120413 11:17:28930601 IsRunning: 1 20120413 11:17:29931843 IsRunning: 1 20120413 11:17:30933098 IsRunning: 1 20120413 11:17:31934366 IsRunning: 0 20120413 11:17:32923594 Handler1: expired. 20120413 11:17:32934692 IsRunning: 0 20120413 11:17:33935922 IsRunning: 0 20120413 11:17:34936638 IsRunning: 0 20120413 11:17:35937905 IsRunning: 0 20120413 11:17:36939133 IsRunning: 0 20120413 11:17:37940407 IsRunning: 0 20120413 11:17:38941043 IsRunning: 0 20120413 11:17:39942319 IsRunning: 0 20120413 11:17:40942662 IsRunning: 0 20120413 11:17:41943989 IsRunning: 0 20120413 11:17:42945284 IsRunning: 0 20120413 11:17:43946555 IsRunning: 0 mbp:stackoverflow samm$