Use of rospy.on_shutdown()

#!/usr/bin/env python

import rospy
from geometry_msgs.msg import Twist

class MoveBB8():
    def __init__(self):
        self.bb8_vel_publisher = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
        self.cmd = Twist()
        self.ctrl_c = False
        self.rate = rospy.Rate(10) # 10hz
    def publish_once_in_cmd_vel(self):
        This is because publishing in topics sometimes fails the first time you publish.
        In continuous publishing systems, this is no big deal, but in systems that publish only
        once, it IS very important.
        while not self.ctrl_c:
            connections = self.bb8_vel_publisher.get_num_connections()
            if connections > 0:
                rospy.loginfo("Cmd Published")
    def shutdownhook(self):
        # works better than the rospy.is_shutdown()
        self.ctrl_c = True

    def move_bb8(self, linear_speed=0.2, angular_speed=0.2):
        self.cmd.linear.x = linear_speed
        self.cmd.angular.z = angular_speed
        rospy.loginfo("Moving BB8!")
if __name__ == '__main__':
    rospy.init_node('move_bb8_test', anonymous=True)
    movebb8_object = MoveBB8()
    except rospy.ROSInterruptException:

I am not able to understand the use of rospy.shutdown()?
what is the use of this function in general , and why it is being used here?
I would really appreciate if someone please help me here.

Hi @prajwalthakur98,

Thanks for asking and welcome to the Community!

rospy.on_shutdown() allows you to specify a function that should be called when ROS has initiated a shutdown (when you press Ctrl + C or the program is ending normally).

This could be used for various purposes, for example, you might want to stop your robot if ROS is shutting down. See an example here: How to stop your robot when ROS is shutting down.

oh i see thank you for your help

1 Like