代码:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
class timer {
public:
typedef boost::function<void( boost::system::error_code, timer& )> handler_function;
timer( boost::asio::io_service &io, boost::asio::deadline_timer::duration_type interval, handler_function handler )
: m_timerImpl( io ), m_duration( interval ), m_handler( handler ) {
}
void start() {
m_timerImpl.expires_from_now( m_duration );
m_timerImpl.async_wait( boost::bind( m_handler, boost::asio::placeholders::error, boost::ref( *this ) ) );
}
void stop() {
m_timerImpl.cancel();
}
private:
boost::asio::deadline_timer m_timerImpl;
boost::asio::deadline_timer::duration_type m_duration;
handler_function m_handler;
};
void timerExpireCallback(boost::system::error_code err, timer &t ) {
static int count = 0;
if (err == 0) {
std::cout << "count: " << count++ << std::endl;
t.start();
}
}
void timerThreadProc( timer &t, boost::asio::io_service &io ) {
t.start();
io.run();
}
int main( int args, char **argv )
{
boost::asio::io_service io;
timer t( io, boost::posix_time::seconds( 1 ), timerExpireCallback );
boost::thread tthread( &timerThreadProc, boost::ref( t ), boost::ref( io ) );
boost::this_thread::sleep_for( boost::chrono::seconds( 9 ) );
t.stop();
tthread.join();
return 0;
}
输出:
count: 0
count: 1
count: 2
count: 3
count: 4
count: 5
count: 6
count: 7