Asio 定时器

这几天看《Boost程序库完全开发指南》的第十二章有介绍Asio的使用方法,介绍很简单,只介绍了定时器、网络通信。下面对书中提到的定时器编程代码(

boost_async_timer_bind.cpp
)如下:

/*
author:AlexChen
date:2014/04/22
#g++ -g -o main boost_async_timer_bind.cpp -lboost_system
*/

#define BOOST_REGEX_NO_LIB
#define BOOST_DATE_TIME_SOURCE
#define BOOST_SYSTEM_NO_LIB
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>

using namespace std;
using namespace boost;
using namespace boost::asio;

void SyncTimer()
{
	io_service ios;
	deadline_timer t(ios,posix_time::seconds(2));
	cout<<t.expires_at()<<"	"<<time(NULL)<<endl;

	t.wait();
	cout<<"Hello!SyncTimer...."<<"	"<<time(NULL)<<endl;
}

void Print(const boost::system::error_code&)
{
	cout<<"Hello!AsyncTimer...."<<"	"<<time(NULL)<<endl;
}

void AsyncTimer()
{
	io_service ios;
	deadline_timer t(ios,posix_time::seconds(2));
	
	cout<<t.expires_at()<<"	"<<time(NULL)<<endl;

	t.async_wait(Print);
	cout<<"It show before t expired..."<<"	"<<time(NULL)<<endl;
	ios.run();
}

class a_timer
{
	private:
		int count;
		int count_max;
		function<void()> f;
		deadline_timer t;

	public:
		template<typename F>
		a_timer(io_service& ios,int x,F func):
		f(func),count_max(x),count(0),
		t(ios,posix_time::millisec(500))
		{
			t.async_wait(boost::bind(&a_timer::call_func,
				this,placeholders::error));
		}
		void call_func(const boost::system::error_code& e)
		{
			if(count >= count_max){
				return;
			}
			++count;
			f();
			t.expires_at(t.expires_at() + posix_time::millisec(500));
			t.async_wait(boost::bind(&a_timer::call_func,this,placeholders::error));
		}
};

void Print1()
{
	cout<<"Hello,Print1..."<<endl;
}

void Print2()
{
	cout<<"Hello,Print2..."<<endl;
}

void TestBind()
{
	io_service ios;
	a_timer at1(ios,5,Print1);
	a_timer at2(ios,5,Print2);
	ios.run();
}

int main()
{
	cout<<endl<<"Test SyncTimer ...."<<endl;
	SyncTimer();
	cout<<endl<<"Test AsyncTimer ...."<<endl;
	AsyncTimer();
	cout<<endl<<"Test TestBind ...."<<endl;
	TestBind();
	cout<<endl<<"successful!..."<<endl;
}


运行结果如下




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值