1. 程式人生 > >(6)使用Timer類

(6)使用Timer類

參考連結:ROS與C++入門教程-使用Timers類

ROS與C++入門教程-使用Timers類

說明:

  • 本教程介紹了roscpp定時器,它允許您安排一個回調發生週期性。

什麼是Timers(定時器)?

  • Timers能讓你以一定的頻率來執行
  • 他們是比ros::Rate更加靈活和有用的形式,ros::Rate在編寫簡單釋出節點和訂閱節點用到。
  • 注意:定時器不是實時的執行緒/核心替換,也不能保證它們的準確度,因為系統負載/功能會有很大的變化。
  • 更多可以參考: roscpp Timers overview

使用定時器

  • 建立定時器象建立訂閱一樣:
ros::Timer timer = n.createTimer(ros::Duration(0.1), timerCallback);
  • 回撥函式:
void timerCallback(const ros::TimerEvent& e);

完整例子

  • 上面為簡單的例子,這裡做一個帶多個定時器的例子。
  • 程式碼如下:
#include "ros/ros.h"

/**
 * This tutorial demonstrates the use of timer callbacks.
 */

void callback1(const ros::TimerEvent&)
{
  ROS_INFO("Callback 1 triggered");
}

void callback2(const ros::TimerEvent&)
{
  ROS_INFO("Callback 2 triggered");
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "talker");
  ros::NodeHandle n;

  /**
   * Timers allow you to get a callback at a specified rate.  Here we create
   * two timers at different rates as a demonstration.
   */
  ros::Timer timer1 = n.createTimer(ros::Duration(0.1), callback1);
  ros::Timer timer2 = n.createTimer(ros::Duration(1.0), callback2);

  ros::spin();

  return 0;
}

程式碼分析:

  • 程式碼:
ros::Timer timer1 = n.createTimer(ros::Duration(0.1), callback1);
ros::Timer timer2 = n.createTimer(ros::Duration(1.0), callback2);
  • 增加兩個定時器,一個100毫秒執行一次,一個1秒執行一次。
  • 執行效果:
[ INFO] 1251854032.362376000: Callback 1 triggered
[ INFO] 1251854032.462840000: Callback 1 triggered
[ INFO] 1251854032.562464000: Callback 1 triggered
[ INFO] 1251854032.662169000: Callback 1 triggered
[ INFO] 1251854032.762649000: Callback 1 triggered
[ INFO] 1251854032.862853000: Callback 1 triggered
[ INFO] 1251854032.962642000: Callback 1 triggered
[ INFO] 1251854033.063118000: Callback 1 triggered
[ INFO] 1251854033.162221000: Callback 1 triggered
[ INFO] 1251854033.262749000: Callback 1 triggered
[ INFO] 1251854033.262864000: Callback 2 triggered
[ INFO] 1251854033.362643000: Callback 1 triggered
[ INFO] 1251854033.463158000: Callback 1 triggered

TimerEvent結構體

  • ros::TimerEvent結構體提供當前定時器的時間資訊
  • 定義如下:
struct TimerEvent
{
  Time last_expected;                     ///< In a perfect world, this is when the last callback should have happened
  Time last_real;                         ///< When the last callback actually happened

  Time current_expected;                  ///< In a perfect world, this is when the current callback should be happening
  Time current_real;                      ///< This is when the current callback was actually called (Time::now() as of the beginning of the callback)

  struct
  {
    WallDuration last_duration;           ///< How long the last callback ran for, always in wall-clock time
  } profile;
};