[Documentation] [TitleIndex] [WordIndex

See also: roscpp Timers Tutorial

roscpp's Timers let you schedule a callback to happen at a specific rate through the same callback queue mechanism used by subscription, service, etc. callbacks.

Timers are not a realtime thread/kernel replacement, rather they are useful for things that do not have hard realtime requirements.

Creating a Timer

Creating a Timer is done through the ros::NodeHandle::createTimer() method:

   1 ros::Timer timer = nh.createTimer(ros::Duration(0.1), timerCallback);

There are a number of different forms of createTimer() which allow you to specify a few different options, as well as a number of different callback types. The general signature is:

   1 ros::Timer ros::NodeHandle::createTimer(ros::Duration period, <callback>, bool oneshot = false);

Callback Signature

The signature for the timer callback is:

   1 void callback(const ros::TimerEvent&);

The ros::TimerEvent structure passed in provides you timing information that can be useful when debugging or profiling.

ros::TimerEvent

Callback Types

roscpp supports any callback supported by boost::bind:

  1. functions
  2. class methods
  3. functor objects (including boost::function)

Functions

   1 void callback(const ros::TimerEvent& event)
   2 {
   3 ...
   4 }
   5 
   6 ...
   7 ros::Timer timer = nh.createTimer(ros::Duration(0.1), callback);

Class Methods

   1 class Foo
   2 {
   3 public:
   4   void Foo::callback(const ros::TimerEvent& event)
   5   {
   6   ...
   7   }
   8 
   9   ros::Timer timer;
  10 };
  11 
  12 ...
  13 // then, during initialization, etc
  14 timer = nh.createTimer(ros::Duration(0.1), &Foo::callback, &foo_object);
  15 
  16 ...
  17 Foo foo_object;

Note that, in this example, the timer object must be a member of the class for callbacks to fire.

Functor Objects

   1 class Foo
   2 {
   3 public:
   4   void operator()(const ros::TimerEvent& event)
   5   {
   6     ...
   7   }
   8 };
   9 
  10 ...
  11 ros::Timer timer = nh.createTimer(ros::Duration(0.1), Foo());

A functor passed to createTimer() must be copyable.

Wall-clock Timers

ros::Timer uses the ROS Clock when available (usually when running in simulation). If you'd like a timer that always uses wall-clock time there is a ros::WallTimer that works exactly the same except replace Timer with WallTimer in all uses, e.g.:

   1 void callback(const ros::WallTimerEvent& event)
   2 {
   3   ...
   4 }
   5 
   6 ...
   7 ros::WallTimer timer = nh.createWallTimer(ros::WallDuration(0.1), callback);

2024-11-16 17:43