class DelayedAction
{
public:
DelayedAction( int expirePeriod, boost::function<void()> callback ):
work( service),
thread( boost::bind( &DelayedAction::run, this)),
timer( service),
m_callback(callback),
m_expirePeriod(expirePeriod)
{}
~DelayedAction()
{
thread.join();
}
void startTimer()
{
}
void on_some_event()
{
startAfter(m_expirePeriod);
}
void stop()
{
timer.cancel();
}
void startAfter( const size_t delay)
{
// no need to explicitly cancel
// timer.cancel();
timer.expires_from_now( boost::posix_time::seconds( delay) );
timer.async_wait( boost::bind( &DelayedAction::action, this, boost::asio::placeholders::error));
}
private:
void run()
{
service.run();
}
// ...
void action(const boost::system::error_code& e)
{
if(e != boost::asio::error::operation_aborted)
std::cout << "action" << std::endl;
m_callback();
}
int m_expirePeriod;
boost::function<void()> m_callback;
boost::asio::io_service service;
boost::asio::io_service::work work;
boost::thread thread;
boost::asio::deadline_timer timer;
};