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

Difference between rospy.spin and rospy.sleep

asked 2019-09-02 15:05:45 -0600

Marseiliais gravatar image

Hi There! Whats the difference between rospy.spin nad rospy.sleep? Does rospy.rate affect rospy.spin?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
10

answered 2019-09-02 17:57:03 -0600

Geoff gravatar image

rospy.spin() will effectively go into an infinite loop until it receives a shutdown signal (e.g. ctrl-c). During that loop it will process any events that occur, such as data received on a topic or a timer triggering, when they occur but otherwise it will sleep. You should use spin() when your node doesn't do anything outside of its callbacks.

rospy.sleep() will do the same as rospy.spin() but only for the length of time you specify. It is used when your node has to do some kind of regular processing in addition to responding to topic events, timer events, etc. For example, a node controlling a motor will need to do some processing at regular intervals to set the motor's desired speed.

(Technically, what both are doing is sleeping your main thread and allowing other, internal threads to do their work.)

edit flag offensive delete link more

Comments

I didn't understand the part "It is used when your node has to do some kind of regular processing in addition to responding to topic events, timer events, etc." ;( Can you please explain in codes what this would mean? If I have two functions in a node. One does image processing and the other one controls the robot. When I use rospy.sleep(20) after each function, It just waits 20 sec to run the loop again. rospy.spin() I used like this-

if __name__ == '__main__':  
    try:
        talker()
        main(sys.argv)
        rospy.spin()
    except rospy.ROSInterruptException:
        pass

Here main() has a call to another function in it's code. So my question is does rospy.spin() run this try: block of code again and again?

Shivam gravatar image Shivam  ( 2021-10-04 08:19:02 -0600 )edit

@Shivam Please open a new question, as comment section is NOT meant to ask a new question.

130s gravatar image 130s  ( 2023-02-17 08:52:14 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2019-09-02 15:05:45 -0600

Seen: 26,755 times

Last updated: Sep 02 '19