定时器的一种实现方式

#include <iostream>
#include <functional>
#include "boost/thread.hpp"

// 定时器回调函数
using  TimerCallBack = std::function<void(void)>;

class CTimer {
public:
    CTimer(TimerCallBack callback, int interval)
        : time_callback_(callback)
        , interval_(interval){
        std::cout << "create timer" << std::endl;
    }

    bool start(){
        std::cout << "start timer" << std::endl;
        exec_ = true;
        thread_ = boost::thread(boost::bind(&CTimer::exec, this));
        return true;
    }

    void stop(){
        std::cout << "stop timer" << std::endl;
        exec_ = false;

        if (thread_.joinable()){
            condition_.notify_all();
            thread_.join();
        }

        return;
    }

private:
    void exec(){
        std::cout << "exec begin..." << std::endl;
        boost::unique_lock<boost::mutex> locker(mutex_);

        while (exec_){
            // 此处建议用boost,std在linux下,如果系统时间经常变化,可能会导致wait卡死!!!
            condition_.wait_for(locker, boost::chrono::milliseconds(interval_), [&]() {return !exec_; });

            if (nullptr != time_callback_) {

                static int call_count = 0;
                std::cout << "callback call, count: " << ++call_count <<std::endl;
                time_callback_();
            }
        }

        std::cout << "exec end" << std::endl;
    }

private:
    bool exec_ = false;
    int interval_ = 500;  // 定时器间隔,单位毫秒
    TimerCallBack time_callback_ = nullptr;
    boost::thread thread_;
    boost::mutex mutex_;
    boost::condition_variable condition_;
};

void OnTimer(){
    static int call_count = 0;
    std::cout << "OnTimer call, count: " << ++call_count << std::endl;
}

int main()
{
    CTimer timer(OnTimer, 500);
    timer.start();
    boost::this_thread::sleep(boost::chrono::seconds(6));
    timer.stop();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值