C++定时器类封装

C++定时器类封装

初步用类封装了写定时器,还有bug,极短的时间去stop时,另一个现在同时tart,有概率触发定时函数被调用,可以加锁等避免

zhi_time.h

#pragma once 

#include <functional>
#include <chrono>
#include <thread>
#include <atomic>
//#include <memory>
#include <mutex>
#include <condition_variable>

class zTimer
{
public:
    zTimer();
    ~zTimer();

    void start(int timer_out_ms, std::function<void()> task);
    void startOnce(int delay, std::function<void()> task);
    void updateTimer(int timer_out_ms);
    void stop();
    bool isRun();

private:
    std::atomic<bool> _run_flag;            // 定时器运行标志
    std::atomic<bool> _uptimer;             // 更新定时器的计时标识
    int _timer_out_ms = 0;                          // 定时器的计时
    std::mutex _time_mutex;
    std::condition_variable _timer_cond;
    bool m_stop_flag = true;
};

zhi_time.cpp

#include "ztimer.h"

zTimer::zTimer():_run_flag(false), _uptimer(false)
{}

zTimer::~zTimer()
{
    stop();
}

void zTimer::start(int timer_out_ms, std::function<void()> task)
{
    if (timer_out_ms <= 0)
        return;
    // is started, do not start again
    if (_run_flag == true) {
        updateTimer(timer_out_ms);
        return;
    }
        
    _run_flag = true;
    _uptimer = true;
    _timer_out_ms = timer_out_ms;
    m_stop_flag = false;

    // start async timer, launch thread and wait in that thread
    std::thread([this, task]() {
        while(_uptimer) {
            _uptimer = false;
            std::unique_lock<std::mutex> time_locker(_time_mutex);
            _timer_cond.wait_for(time_locker, std::chrono::milliseconds(_timer_out_ms));
        }

        if (_run_flag) {
            _run_flag = false;
            _timer_out_ms = 0;
            task();
        }
        m_stop_flag = true;
    }).detach();
}

void zTimer::startOnce(int delay, std::function<void()> task)
{
    std::thread([delay, task]() {
        std::this_thread::sleep_for(std::chrono::milliseconds(delay));
        task();
    }).detach();
}

void zTimer::updateTimer(int timer_out_ms)
{
    if (timer_out_ms <= 0)
        return;
        
    _uptimer = true;
    _timer_out_ms = timer_out_ms;
    _timer_cond.notify_one();
}

void zTimer::stop()
{
    // do not stop again
    if (!_run_flag)
        return;

    _run_flag = false;
    _uptimer = false;
    _timer_out_ms = 0;
    _timer_cond.notify_one();
    std::this_thread::sleep_for(std::chrono::milliseconds((2)));
}

bool zTimer::isRun()
{
    return _run_flag;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值