boost 定时器 demo

代码:

#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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值