Search code examples
pythonubuntu-16.04ros

Improve the way of killing a node after an specific amount of time


I am publishing a message to an specific topic and I need it to stop after a set amount of time.The publishing process consist of loop thats continuously sends info to the topic.

This is the loop I need to stop after an specific amount of time given by user input.

  while not rospy.is_shutdown(): 
        movement_cmd.linear.x = 0
        movement_cmd.linear.y = 0
        movement_cmd.linear.z = 0 
        movement_cmd.angular.x = 0 
        movement_cmd.angular.y = 0               
        movement_cmd.angular.z = 0 
        rospy.logdebug("Publishing")
        movement_publisher.publish(movement_cmd)
        rate.sleep()

Edit :

This is the user input

time = float(sys.argv[2])

For example if time = 2.5 then the loop should publish for 2.5 seconds, after that it should stop and the code would end.

I managed to stop the loop after sometime by setting the publish frequency to 20hz. This means it will publish every 0.05 seconds , so I added a variable named counter and every time the loop publishes it adds +0.05 to the counter variable.Then counter is compared with time and if both have the same value I end the loop using:

if counter >= time:
        break

Is there a way to improve this by using any other function?


Solution

  • You can try rospy Timer class to publish on a topic for a certain period of time. It allows to trigger events at a certain time.

    def stop_callback(event):
        rospy.signal_shutdown("Just stopping publishing...")
    
    time = float(sys.argv[2]) 
    rospy.Timer(rospy.Duration(time), stop_callback)
    
    while not rospy.is_shutdown(): 
        movement_cmd.linear.x = 0
        movement_cmd.linear.y = 0
        movement_cmd.linear.z = 0 
        movement_cmd.angular.x = 0 
        movement_cmd.angular.y = 0               
        movement_cmd.angular.z = 0 
        rospy.logdebug("Publishing")
        movement_publisher.publish(movement_cmd)
        rate.sleep()
    

    Learn more about how to use Timer class from here.