定时器定以一定的速率定时的调用回调函数。They are a more flexible and useful form of the ros::Rate used in the Writing a Simple Publisher and Subscriber tutorial.
Note that Timers are not a realtime thread/kernel replacement, and make no guarantees about how accurate they are, which can vary wildly because of system load/capabilities.
创建一个定时器的工作原理非常类似于创建一个订阅者:
ros::Timer timer = n.createTimer(ros::Duration(0.1), timerCallback);
回调函数的格式如下:
void timerCallback(const ros::TimerEvent& e);
ow that you've seen the basics, let's go through a larger example, with multiple Timers.
#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毫秒,并且其中一个触发每一秒。如果你运行这个程序,它应该输出类似如下:
[ 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
...
The ros::TimerEvent structure provides you information about the timing of the current timer. Here is its definition:
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;
};