15.ROS2 time related API

 

1. Introduction to Time-Related APIs

ROS2's time-related APIs include Rate, Time, Duration, and operations on Time and Duration. These are explained below.

2. create_rate

ROS2 also provides the create_rate function, a tool for controlling loop execution frequency. Its core function is to periodically execute a section of code at a fixed frequency. Rate ensures the stability of the loop execution frequency by controlling the "sleep time" of the loop. Remember that Rate should generally not be used directly in the main thread, as doing so will permanently block callback events. It is generally only used in programs with multi-threaded callbacks or in child threads.

How it works:

  1. Records the start time of each loop;
  2. Executes the code within the loop;
  3. Calculates the difference between the current loop's actual duration and the target interval;
  4. Automatically sleeps for the corresponding difference, ensuring that the interval from the start of one loop to the start of the next strictly equals the target interval (e.g., 100 milliseconds).

While both Rate and Timer can implement periodic execution, their application scenarios differ:

FeaturesRateTimer
ImplementationBased on active sleep within a loop (blocking the current thread)Based on callback functions (non-blocking, triggered by the ROS 2 event loop)
Applicable ScenariosSuitable for loops that need to execute at a fixed frequency within the same thread (such as main control logic)Suitable for periodic tasks that need to execute asynchronously (without blocking the main thread)
FlexibilityDirect control flow within the loop (such as break exit)Callback execution must be controlled using flags or other methods

 

image-20250905155834618

 

image-20250905155916058

 

image-20250905155949678

 

3. Timer Application

image-20250905160115901

 

image-20250905155916058

 

image-20250905160239330

 

4. Get the Current Time with get_clock

image-20250905160541502

 

image-20250905155916058

image-20250905160631573

 

5. Time and Duration

image-20250905160751388

 

image-20250905155916058

 

image-20250905160840013