rospy.Rate(10). What will happen if the message processing inside the loop takes longer than 0.1 seconds?import rospy from std_msgs.msg import String def talker(): pub = rospy.Publisher('chatter', String, queue_size=10) rospy.init_node('talker', anonymous=True) rate = rospy.Rate(10) # 10hz while not rospy.is_shutdown(): rospy.loginfo('Hello ROS') pub.publish('Hello ROS') # Simulate long processing rospy.sleep(0.15) rate.sleep() if __name__ == '__main__': try: talker() except rospy.ROSInterruptException: pass
rospy.Rate.sleep() works when the loop takes longer than the intended rate period.The rospy.Rate(10) tries to maintain a 10 Hz rate by sleeping for the remaining time in each loop. If the processing inside the loop takes longer than 0.1 seconds, the rate.sleep() will not sleep and the loop runs slower than 10 Hz.
timer_callback every 0.5 seconds?def timer_callback(event): rospy.loginfo('Timer triggered')
rospy.Timer.The rospy.Timer constructor requires a rospy.Duration object as the first argument and a callback function as the second. The callback should be passed as a function reference, not called.
import rospy from std_msgs.msg import String def callback(msg): rospy.sleep(0.05) # Simulate processing time rospy.loginfo('Received message') rospy.init_node('listener') rospy.Subscriber('chatter', String, callback, queue_size=1) rospy.spin()
The subscriber processes each message in 0.05 seconds, so it can handle 20 messages per second. Since the publisher sends at 50 Hz and the queue size is 1, older messages are dropped, so the subscriber effectively processes at 20 Hz.
import rospy from std_msgs.msg import String def talker(): pub = rospy.Publisher('chatter', String, queue_size=10) rospy.init_node('talker', anonymous=True) rate = rospy.Rate(5) # 5hz while not rospy.is_shutdown(): pub.publish('Hello') pub.publish('Hello again') rate.sleep() if __name__ == '__main__': try: talker() except rospy.ROSInterruptException: pass
pub.publish is called inside the loop.The loop publishes two messages every cycle. Since the loop runs at 5 Hz, the total messages published per second are 10, doubling the expected frequency.
import rospy def callback_a(event): rospy.sleep(0.1) rospy.loginfo('Timer A callback') def callback_b(event): rospy.sleep(0.1) rospy.loginfo('Timer B callback') rospy.init_node('multi_timer') timer_a = rospy.Timer(rospy.Duration(0.2), callback_a) timer_b = rospy.Timer(rospy.Duration(0.5), callback_b) rospy.spin()
With a single-threaded spinner, callbacks are executed one after another. If a callback takes 0.1 seconds, and Timer A triggers every 0.2 seconds, the callbacks may queue up causing delays. Timer B's callback also adds to the queue, so callbacks may not run exactly on schedule.
