When you call expires_from_now()
on a running timer,
the timer is cancelled, and a new timer is called.
So the associated handler is called.
It is easy to discriminate in the handler
between a cancelled and an expired timer.
Yet, I am wondering, if there is a way to discriminate
between a expired and a retriggered timer.
In both instances the handler is called
with error_code operation_aborted
.
Or maybe I missing some details.
以下守则产生了以下产出:
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.
This suggests that the handler is not able to implement actions for a cancelled handler, because retriggering a timer will call the same handler and thereby execute the same actions. Which is probably not the intended behaviour.
#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
}