Fast DDS中的定时器

目录

定时器使用

Fast DDS中的定时器主要有三个类组成:ResourceEvent,TimedEventImpl, TimedEvent。

ResourceEvent中管理定时器线程,当用户启动定时器时,需要开启ResourceEvent中的定时器线程,具体有以下步骤:

  1. 创建一个TimeEvent对象。在创建对象时,你需要提供一个回调函数,以及一个时间间隔。
  2. 启动TimeEvent。你可以调用TimeEvent的restart()函数来启动或重启定时器。
  3. 在回调函数中处理定时事件。当定时器到达预设的时间间隔时,会自动调用你提供的回调函数。
  4. 停止TimeEvent。你可以调用TimeEvent的cancel()函数来停止定时器。

使用代码如下:

cpp 复制代码
// 定义两个变量:
ResourceEvent test_resource_;
TimedEvent* test_timer_{nullptr};
// 开启ResourceEvent中的定时器,并创建TimedEvent实例:
test_timer_= new TimedEvent(test_resource_, 
                                           std::bind(&TestClass::timer_callback, this), 
                                           interval_time_.minimum_separation.seconds * 1000 + att.interval_time_.minimum_separation.nanosec / 1000000
                                      );
test_timer_->restart_timer();

此时就开始按照指定的周期开始调用定时器函数&TestClass::timer_callback。

代码分析

类图如下:

TODO

第一步,初始化一个ResourceEvent 实例。

ResourceEvent 中的变量说明:

cpp 复制代码
std::atomic<bool> stop_{ false };  // 定时器线程是否执行
TimedMutex mutex_;    // 用来保护ResourceEvent内部的数据成员
    //! Used to warn about changes on allow_vector_manipulation_.
    TimedConditionVariable cv_manipulation_;

    //! Flag used to allow a thread to manipulate the timer collections when the execution thread is not using them.
    bool allow_vector_manipulation_ = true;

    //! Used to warn there are new TimedEventImpl objects to be processed.
    TimedConditionVariable cv_;

    //! 创建的定时器个数
    size_t timers_count_ = 0;

    //! Collection of events pending update action.
    std::vector<TimedEventImpl*> pending_timers_;

    //! Collection of registered events waiting completion.
    std::vector<TimedEventImpl*> active_timers_;

    //! Prevents iterator invalidation when active_timers are manipulated inside loops
    std::atomic<bool> skip_checking_active_timers_;

    //! 当前时间
    std::chrono::steady_clock::time_point current_time_;

    //! 定时器线程
    std::thread thread_;
相关推荐
橘颂TA6 分钟前
【Linux】从 “抢资源” 到 “优雅控场”:Linux 互斥锁的原理与 C++ RAII 封装实战(Ⅰ)
linux·运维·服务器·c++·算法
枫叶丹421 分钟前
【Qt开发】Qt系统(三)->事件过滤器
java·c语言·开发语言·数据库·c++·qt
坐怀不乱杯魂1 小时前
Linux - 缓存利用率
linux·c++·缓存
leiming61 小时前
c++ for_each算法
开发语言·c++·算法
_OP_CHEN1 小时前
【算法基础篇】(四十一)数论之约数问题终极攻略:从求单个约数到批量统计
c++·算法·蓝桥杯·数论·约数·算法竞赛·acm/icpc
草莓熊Lotso1 小时前
从冯诺依曼到操作系统:打通 Linux 底层核心逻辑
linux·服务器·c++·人工智能·后端·系统架构·系统安全
yuanmenghao1 小时前
自动驾驶中间件iceoryx - 内存与 Chunk 管理(一)
c++·vscode·算法·链表·中间件·自动驾驶·柔性数组
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——面试题 01.02 :判定是否互为字符串重排
c++·算法·leetcode·职场和发展·结构与算法
HABuo1 小时前
【Linux进程(二)】操作系统&Linux的进程状态深入剖析
linux·运维·服务器·c语言·c++·ubuntu·centos
糯诺诺米团1 小时前
C++多线程打包成so给JAVA后端(Ubuntu)<2>
java·开发语言·c++