目前没有看见能够直接拿来就能用的定时器,在工作中正好要用到,就封装了一个:
- async_timer.h
#ifndef _ASYNC_TIMER_H_
#define _ASYNC_TIMER_H_
#include <boost/asio/steady_timer.hpp>
#include <boost/chrono/duration.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/asio.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
class AsyncTimer
{
private:
int m_count, m_countMax, m_duration;
boost::asio::steady_timer m_timer;
public:
AsyncTimer(boost::function<void()> func, int milliSec, int max);
void CallFunc(const boost::system::error_code&);
void Run();
void Cancel();
};
#endif
- async_timer.cpp
#include <time.h>
#include <chrono>
#include "async_timer.h"
AsyncTimer::AsyncTimer(boost::function<void()> func, int milliSec , int max )
:m_ios()
,m_func(func)
,m_countMax(max)
,m_duration(milliSec)
,m_count(0)
,m_timer(m_ios)
{
time_t tt = time(NULL);//这句返回的只是一个时间cuo
tm* t= localtime(&tt);
m_timer.expires_from_now(std::chrono::milliseconds(m_duration));
m_timer.async_wait(boost::bind(&AsyncTimer::CallFunc, this, boost::asio::placeholders::error));
boost::thread th(boost::bind(&AsyncTimer::Run, this));
th.detach();
}
void AsyncTimer::CallFunc(const boost::system::error_code& err)
{
if(err)
{
printf("cancel the timer.");
return;
}
m_func();
++m_count;
if(m_count >= m_countMax)
{
return;
}
m_timer.expires_from_now(std::chrono::milliseconds(m_duration));
m_timer.async_wait(boost::bind(&AsyncTimer::CallFunc, this, boost::asio::placeholders::error));
}
void AsyncTimer::Run()
{
m_ios.run();
}
void AsyncTimer::Cancel()
{
m_timer.cancel();
}
- main.cpp
#include "async_timer.h"
#include <stdio.h>
void print( )
{
printf("hello,world!\n");
}
int main(int argc , char ** argv)
{
printf("start\n");
AsyncTimer timer(print, 5000, 1);
printf("end\n");
}
- 注意:
这里的回掉函数可以是:
带参数普通函数
void print(int i )
{
std::cout<<"hello,world!\n" << i << std::endl;
}
boost::function<void()> func = boost::bind(&print, 2);
成员函数
boost::function<void()> func = boost::bind(&Class Name::funcname, this, ...);