//
// fox_timer.hpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014-2015 yoen.xu (181471112 at qq dot com)
//
//说明
//eg: fox_timer<T>::run(io_, func, interval);
// T 为func的返回类型,当T为int的时候(范围值-1代表取消定时器,0定时器时间不变 >0重置定时器时间)
// 可以使用cancle()来取消定时器
#ifndef FOX_TIMER_HPP
#define FOX_TIMER_HPP
#if defined(_MSC_VER) && (_MSC_VER >=1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/asio.hpp>
#include <boost/make_shared.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/utility/result_of.hpp>
using namespace boost;
using namespace boost::asio;
namespace fox{
// an deadline timer
template <typename ReturnType>
class fox_timer:public enable_shared_from_this< fox_timer<ReturnType> >{
private:
//default dead time(seconds)
const static long DEFAULT_INTERVAL_SECONDS = 3;
function<ReturnType()> f_;
//async_wait callback function
deadline_timer t_;
long interval_;
void do_wait(){
t_.expires_from_now(posix_time::seconds(interval_));
t_.async_wait(boost::bind(&fox_timer::call_func,shared_from_this(),boost::asio::placeholders::error));
}
void call_func(const system::error_code& err){
if (err){
return;
}
else{
assert(!f_.empty());
if (typeid(int) == typeid(ReturnType))
{
int iret = f_();
assert(iret >= -1);
switch(iret){
case -1:
return;
case 0:
break;
default:
set_interval(iret);
}
}else {
f_();
}
do_wait();
}
}
public:
template<typename WaitHandler> static void run(io_service& ios,WaitHandler func,const long seconds=DEFAULT_INTERVAL_SECONDS){
boost::make_shared< fox_timer<ReturnType> >(ios, func,seconds)->start();
}
template<typename WaitHandler>
explicit fox_timer(io_service& ios, WaitHandler func, const long seconds=DEFAULT_INTERVAL_SECONDS)
:f_(func),interval_(seconds)
,t_(ios,posix_time::seconds(seconds))
{
assert(typeid(boost::result_of<WaitHandler()>::type) == typeid(ReturnType));
}
~fox_timer()
{
cancle();
}
void set_interval(const long seconds){
interval_ = seconds;
}
void start(){
do_wait();
}
void cancle(){
t_.cancel();
}
};
}//namespace fox
#endif //FOX_TIMER_HPP共享boost::deadline_timer封装模板,可以接受任何函数对象
原文:http://blog.csdn.net/kluleia/article/details/43560085