Main Content

waitfor

Pause code execution to achieve desired execution rate

Since R2022b

    Description

    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.

    example

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

    Examples

    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.

    reset(r)
    for i = 1:10
    	time = r.TotalElapsedTime;
    	fprintf('Iteration: %d - Time Elapsed: %f\n',i,time)
    	waitfor(r);
    end
    Iteration: 1 - Time Elapsed: 0.007255
    Iteration: 2 - Time Elapsed: 0.505368
    Iteration: 3 - Time Elapsed: 1.005004
    Iteration: 4 - Time Elapsed: 1.501875
    Iteration: 5 - Time Elapsed: 2.003129
    Iteration: 6 - Time Elapsed: 2.509410
    Iteration: 7 - Time Elapsed: 3.000233
    Iteration: 8 - Time Elapsed: 3.500451
    Iteration: 9 - Time Elapsed: 4.000128
    Iteration: 10 - Time Elapsed: 4.500364
    

    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