ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Revision history [back]

If I'm understanding your question you want run a while loop for a specific period of time to repeatedly performing some processing or action. This is perfectly possible, although it's not really a function since this is part of the structure of your own program you need to write.

Using ros::Time you can record the time before your while loop, then continue iterating until a certain amount of time has passed. This structure would look like this:

ros::Time startTime = ros::Time::now();
ros::Duration loopDuration(5.0); // 5 seconds
while (ros::Time::now() < startTime+loopDuration)
{
  // do your processing here
}

Since ROS is an event driven system it's not a good idea to execute a block of code for a long period of time without checking for messages, so it's good practice to add a call to spinOnce in there to keep up-to date with message processing.

ros::Time startTime = ros::Time::now();
ros::Duration loopDuration(5.0); // 5 seconds
while (ros::Time::now() < startTime+loopDuration)
{
  // do your processing here

  ros::spinOnce(); //  check for messages
}

You may also want your loop run at a particular frequency as opposed to going 'flat out' as the previous two will. Using the ros::Rate object you can control this as below:

ros::Time startTime = ros::Time::now();
ros::Duration loopDuration(5.0); // 5 seconds
ros::Rate loopRate(30.0); // 30 Hz
while (ros::Time::now() < startTime+loopDuration)
{
  // do your processing here

  ros::spinOnce(); //  check for messages

  loopRate.sleep(); // delay loop so it doesn't run faster than 30 Hz
}

Hope this helps you get this working the way you want.