Hi @vasank1958,
Code 2 is not publishing continuously because it’s just “running out”; by the time the last line is executed, there’s nothing more happening, so the program ends, and forces ROS to shutdown.
Code 1, however, does not end because it has a while loop that keeps it alive unless ROS is shutting down.
Usually ROS does NOT shutdown unless you press CTRL + C
or there’s an error, or the code itself stops executing (like in your case).
As for the difference you asked:
- Usually, you use
while not rospy.is_shutdown()
when you want to publish to a topic at a certain rate, but in that case you userospy.Rate.sleep()
, notrospy.sleep()
like you did. Read more here: Proper use of rospy.Rate or ros::Rate - You typically use
rospy.spin()
on the last line of the code when a subscriber is involved. This ensures that the program will not “run out” like your code-2 and that your subscribed messages will arrive. Read more aboutrospy.spin()
here: What is rospy.spin(), ros::spin(), ros::spinOnce(), and what are they for?