Services_quiz: wait for n seconds?

I think I’m missing something basic in the services_quiz.

It seems that all of the example services were “do something that takes as long as it takes, and respond when it is done. I’ll wait” But the services_quiz is “do something, and take the amount of time I tell you to take, and then tell me you did it.” So, I’ve got a service, and when it receives a message request, that triggers a callback, which can start publishing the rotate cmd_vel, and then it… well… I guess it blocks the thread for the specified number of seconds with some kind of sleep function, then sets the rotation speed back to 0.0 and returns that it did a good job. I don’t love blocking the thread, but if I understand correctly, if I exit my callback, ROS will send a response to the client, and I think I understand that I shouldn’t do that until the end of the requested rotation time? So, blocking the thread and delaying the exit from that callback would seem to meet the requirements of the quiz as I understood them, but how do I sleep or wait for the specified number of seconds before I stop the rotation?

You can use the sleep method from the timer as service callback is triggered as follows:

import timer

i = 0

while (i <= request.time):
# publish the velocity
i += 1
timer.sleep(duration in seconds)

Or use the get_clock method to invoke sleep_for where you can define the time sleep.


Thanks for the reply. I appreciate it.

I actually read ahead a little and in the section on actions, there is some sample code that uses rclcpp::Rate to set up a loop_rate, and then (apparently) you can call the sleep method at the end of a loop (or presumably anywhere?) and I suppose it will sleep until the specified period after the last time it was called? So, if I set up a for loop to loop num_seconds times, and just rate.sleep() inside it, that will presumably do the trick.
Assuming I initialize it with a “rate” of 1 second, and initialize the rate variable immediately before the start of my loop.

Also, it looks like you are using python. I failed to specify that I am in the cpp course.

but of course, re-reading my reply, if I have to initialize it with a particular rate, I should likely just initialize it with the desired num_seconds and call .sleep() once instead of in a loop. I didn’t think that one all the way through…

Hello @jimparker .

In C++, to sleep (wait) in a thread you can use the following code: std::this_thread::sleep_for(std::chrono::seconds{time_in_seconds});

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.