使用boost的deadline_timer实现一个异步定时器

简介: 概述 最近在工作上需要用到定时器,然后看到boost里面的deadline_timer可以实现一个定时器,所以就直接将其封装成了ATimer类,方便使用,ATimer有以下优点: 可以支持纳秒、毫秒、秒、分、小时定时。

概述

最近在工作上需要用到定时器,然后看到boost里面的deadline_timer可以实现一个定时器,所以就直接将其封装成了ATimer类,方便使用,ATimer有以下优点:

  1. 可以支持纳秒、毫秒、秒、分、小时定时。
  2. 可以随时停止定时器。
  3. 支持单次调用。
  4. 因为使用了deadline_timer,所以定时比较准确。

ATimer和Qt的QTimer使用方法类似,若没有类似的Timer类,使用最原始的方法,我们的代码可能会是这样的:

m_timerThread = std::thread([this]
{
    while (!m_bThreadStoped) { ++m_sleepCount; Sleep(SLEEP_DURATION_TIME); if (m_sleepCount == m_sleepAllCount) { m_sleepCount = 0; doSomeThing(); } } });

若使用QTimer的话,书写是这样的:

QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(update())); timer->start(1000);

再来看看ATimer的使用:

ATimer<> t;
t.bind([]{ std::cout << "Hello C++" << std::endl; }); t.start(1000);

从上面的例子可以看到,QTimer和ATimer的使用都非常方便,接下来看看ATimer的具体实现:

// ATimer.hpp
#ifndef _ATIMER_H #define _ATIMER_H #include <vector> #include <thread> #include <atomic> #include <functional> #include <boost/timer.hpp> #include <boost/asio.hpp> template<typename Duration = boost::posix_time::milliseconds> class ATimer { public: ATimer() : m_timer(m_ios, Duration(0)), m_isSingleShot(false) {} ~ATimer() { stop(); } void start(unsigned int duration) { if (m_ios.stopped()) { return; } m_isActive = true; m_duration = duration; m_timer.expires_at(m_timer.expires_at() + Duration(m_duration)); m_func = [this] { m_timer.async_wait([this](const boost::system::error_code&) { for (auto& func : m_funcVec) { func(); } if (!m_isSingleShot) { m_timer.expires_at(m_timer.expires_at() + Duration(m_duration)); m_func(); } }); }; m_func(); m_thread = std::thread([this]{ m_ios.run(); }); } void stop() { m_ios.stop(); if (m_thread.joinable()) { m_thread.join(); } m_isActive = false; } void bind(const std::function<void()>& func) { m_funcVec.emplace_back(func); } void setSingleShot(bool isSingleShot) { m_isSingleShot = isSingleShot; } bool isSingleShot() const { return m_isSingleShot; } bool isActive() const { return m_isActive; } private: boost::asio::io_service m_ios; boost::asio::deadline_timer m_timer; std::function<void()> m_func = nullptr; std::vector<std::function<void()>> m_funcVec; std::thread m_thread; unsigned int m_duration = 0; std::atomic<bool> m_isSingleShot; bool m_isActive = false; }; #endif 

下面是ATimer的具体使用例子:

// main.cpp
#include <iostream> #include "ATimer.hpp" void test() { std::cout << "Timer thread id: " << std::this_thread::get_id() << std::endl; } int main() { std::cout << "Main thread id: " << std::this_thread::get_id() << std::endl; ATimer<boost::posix_time::minutes> t0; t0.setSingleShot(true);// 单次调用 t0.bind(test); t0.start(1);// 一分钟之后调用 ATimer<> t;//默认使用毫秒定时器 t.bind(test); t.bind([]{ std::cout << "Hello C++" << std::endl; }); t.start(1000);//每1000ms调用一次 std::cin.get(); t0.stop(); t.stop(); std::cout << "Tiemr stop" << std::endl; std::cin.get(); std::cout << "Process end" << std::endl; return 0; }

from:http://www.cnblogs.com/highway-9/p/5737421.html
目录
相关文章
|
9月前
|
数据采集 人工智能 运维
广东电网的步步为营,从计量云到电力运维的AI指挥官
2024年8月26日广东电网计量自动化系统3.0单轨运行,在新型电力系统建设蓝图上写下浓墨重彩的一笔。 至今,这个存储容量达10PB、数据入库400万条每秒,覆盖5000万广东电力用户的“计量大脑”,创下全国规模之最。在这一过程中,广东电网携手阿里云等核心合作伙伴,突破了一个又一个技术难点,也实现了电力计量从“人工经验驱动”向“数据智能决策”的跨越式发展。
432 11
|
文字识别 计算机视觉 开发者
基于QT的OCR和opencv融合框架FastOCRLearn实战
本文介绍了在Qt环境下结合OpenCV库构建OCR识别系统的实战方法,通过FastOCRLearn项目,读者可以学习Tesseract OCR的编译配置和在Windows平台下的实践步骤,文章提供了技术资源链接,帮助开发者理解并实现OCR技术。
849 9
基于QT的OCR和opencv融合框架FastOCRLearn实战
|
机器学习/深度学习 自然语言处理
掩码语言模型(MLM)
【10月更文挑战第6天】掩码语言模型(MLM)
|
算法 计算机视觉
基于Chan-Vese算法的图像边缘提取matlab仿真
**算法预览展示了4幅图像,从边缘检测到最终分割,体现了在matlab2022a中应用的Chan-Vese水平集迭代过程。核心代码段用于更新水平集并显示迭代效果,最后生成分割结果及误差曲线。Chan-Vese模型(2001)是图像分割的经典方法,通过最小化能量函数自动检测平滑区域和清晰边界的图像分割,适用于复杂环境,广泛应用于医学影像和机器视觉。**
|
Linux C++ Windows
基于Asio库的定时器,封装实现好用的定时任务
基于Asio库的定时器,封装实现好用的定时任务
|
Linux C++ Windows
C++:在程序中获取全球唯一标识号(GUID或UUID)
Windows:使用CoCreateGuid函数(GUID) #include #include #define GUID_LEN 64 int main(int argc, char* argv[]){ char buffer[GUID_LEN] = { 0 }; GUID guid; ...
9541 121
|
PyTorch 算法框架/工具 机器学习/深度学习
GoogLeNet InceptionV3代码复现+超详细注释(PyTorch)
GoogLeNet InceptionV3代码复现+超详细注释(PyTorch)
768 0
|
数据采集 安全 BI
瑞数API安全审计系统首发
API资产管理为重点,API安全审计为核心
592 0
|
存储 移动开发 Linux
Linux项目实战系列之:再谈一次GPS数据解析
Linux项目实战系列之:再谈一次GPS数据解析
|
SQL 前端开发 JavaScript
基于java+springboot的旅游信息网站、旅游景区门票管理系统
该系统是基于java+springboot开发的旅游景区门票管理系统。是给师弟开发的大四实习作品。学习过程中,遇到问题可以咨询github作者。
658 0