定时器使用
Fast DDS中定时器是通过一条线程运行多个定时器的模式,线程的生命周期由ResourceEvent管理,并且用户定义的TimedEvent也是在ResourceEvent调度执行定时器函数,所以,当用户定义1个或多个定时器之前时,首先需要初始化一个ResourceEvent对象,然后再创建TimedEvent定时器,具体有以下步骤:
- 创建一个ResourceEvent对象,并调用其init_thread方法构造eprosima::thread对象,此时,ResourceEvent创建的线程函数开始运行;
- 构造TimedEvent对象,需要提供提供一个回调函数,和上一步创建的ResourceEvent对象;
- 调用TimedEvent对象的restart_timer()方法将创建的TimedEvent对象添加到ResourceEvent对象用于管理TimedEventImpl的数据成员中,定时器开始运行
- 停止TimeEvent。你可以调用TimeEvent的cancel()函数来停止定时器。
Fast DDS中使用代码如下(RTPSParticipantImpl类中定义的ResourceEvent举例):
// ResourceEvent的构造和线程初始化
ResourceEvent mp_event_thr;
mp_event_thr.init_thread(thr_config, "dds.ev.%u", id_for_thread);
// PDP中TimedEvent的构造
TimedEvent* resend_participant_info_event_;
resend_participant_info_event_ = new TimedEvent(mp_RTPSParticipant->getEventResource(),
[&]() -> bool
{
announceParticipantState(false);
set_next_announcement_interval();
return true;
},
0);
// 开启ResourceEvent中的定时器
resend_participant_info_event_->restart_timer();->restart_timer();
代码分析
Fast DDS中的定时器主要有三个类组成:ResourceEvent,TimedEventImpl, TimedEvent。
类图如下:
定时器的核心实现放在TimedEventImpl中,所以核心类有两个:ResourceEvent和TimedEventImpl,TimedEvent主要用于为用户提供接口。
时序图