Main Content


Pause code execution to achieve desired execution rate

Since R2022b



    waitfor(rate) pauses execution of the ROS 2 loop execution object rate until the code reaches the desired execution rate. The function accounts for the time spent executing code between waitfor calls.

    numMisses = waitfor(rate) returns the number of iterations missed while executing code between calls.


    collapse all

    Create a ROS 2 node.

    node = ros2node("/myNode");

    Create a publisher to publish a standard integer message.

    pub = ros2publisher(node,"/my_int","std_msgs/Int64");

    Create a ros2rate object that runs at 2 Hz.

    r = ros2rate(node,2);

    Start loop that prints the current iteration and time elapsed. Use waitfor to pause the loop until the next time interval. Reset r prior to the loop execution. Notice that each iteration executes at a 1-second interval.

    for i = 1:10
    	time = r.TotalElapsedTime;
    	fprintf('Iteration: %d - Time Elapsed: %f\n',i,time)
    Iteration: 1 - Time Elapsed: 0.008025
    Iteration: 2 - Time Elapsed: 0.507448
    Iteration: 3 - Time Elapsed: 1.004842
    Iteration: 4 - Time Elapsed: 1.503426
    Iteration: 5 - Time Elapsed: 2.004145
    Iteration: 6 - Time Elapsed: 2.510637
    Iteration: 7 - Time Elapsed: 3.000392
    Iteration: 8 - Time Elapsed: 3.500345
    Iteration: 9 - Time Elapsed: 4.000225
    Iteration: 10 - Time Elapsed: 4.500291

    Input Arguments

    collapse all

    ros2rate object, specified as a handle. This object contains the information for the desired rate and other information about the execution. See ros2rate for more information.

    Output Arguments

    collapse all

    Number of missed task executions, returned as a scalar. waitfor returns the number of desired time steps missed based on the LastPeriod and DesiredRate properties of the ros2rate object rate. For example, if the desired rate is 1 Hz and the last period was 3.2 seconds, numMisses is 3.

    Version History

    Introduced in R2022b

    See Also