异步定时器

目前没有看见能够直接拿来就能用的定时器,在工作中正好要用到,就封装了一个:

  • 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, ...);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值