What is difference between rospy.spin() and while not rospy.is_shutdown()?

code-1

    import rospy
    from std_msgs.msg import Int32
    rospy.init_node('pub')
    publisherobj = rospy.Publisher('/top',Int32,queue_size=1)
    obj = Int32()
    while not rospy.is_shutdown():
                  obj.data = 536
                  publisherobj.publish(obj)
                  rospy.sleep(1)

code-2

    import rospy
    from std_msgs.msg import Int32
    rospy.init_node('pub')
    publisherobj = rospy.Publisher('/top',Int32,queue_size=1)
    obj = Int32()
    obj.data = 536
    publisherobj.publish(obj)
    rospy.sleep(1)
    rospy.spin()

In both cases the node doesn’t exit , however only cod 1 continues to publish information to topic same is not for code block 2 why ?

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 shutdown not 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:

@bayodesegun sir I think I made a mistake in the question , The code block 2 actually ends with rospy.spin(). In this case why is the publisher not constantly printing ?

@vasank1958 Adding rospy.spin() at the end should keep the program from stopping, but technically the program isn’t doing anything anymore because nothing else happens after this. spin() does not make the program go back and execute other statements, in case that’s what you are thinking.

So in this case, and for most cases involving only publishers, rospy.spin() is not appropriate.

As I mentioned earlier, rospy.spin() is usually used when a subscriber is involved. The reason it works with a subscriber is that even though it seems the program has reached the last line, the subscriber runs in a separate thread and calls a callback function from time to time, so things keep happening.