You cannot control how often your subscriber callback is called. roscpp will attempt to call your callback once for every message that is received.
If you can change the publish rate, that's the most obvious way to change how often your callback is called, but it will affect every node subscribing to that topic, and how you change the publish rate depends on the node that is publishing. You don't say which node is publishing these messages, so I can't give more specific advice.
If you can't change the publisher (either it affects other nodes or the code doesn't allow it), you can use the topic_tools throttle node to subscribe to the topic and publish it at a slower rate.
Depending on what you're trying to do, you could also implement the callback throttling in your own code; I see two ways to do this:
- keep a variable that tracks the last time you processed a message, and check that in your callback to figure out when to do the actual message processing.
- Have a simple callback that only store the most recent message in a global or class variable, and then use a timer to process that data.
There are additional tradeoffs between all of these approaches, but without knowing why you want to subscribe at a slower rater, I can't give more specific advice.
Originally posted by ahendrix with karma: 47576 on 2016-07-31
This answer was ACCEPTED on the original site
Post score: 5
Original comments
Comment by yongqi on 2016-07-31:
Thanks for your reply. I am using python and Turtlebot. The Subscriber:rospy.Subscriber('/moblie_base/sensors/core', SensorState, self.pick_up)
,
Publisher:self.vol_pub = rospy.Publisher('volice', String, queue_size=1)
Publisher will publish topic in pick_up
, can I set the Subscriber interval?
Comment by ahendrix on 2016-08-01:
No; the subscribe cannot set the interval. My answer was written with roscpp in mind, but the advice applies to Python too.
Comment by yongqi on 2016-08-01:
Thanks a lot
Comment by Airuno2L on 2016-08-01:
(I edited the link to topic_tools throttle, it was linked to this page)
Comment by huckl3b3rry87 on 2017-08-01:
Would it also be possible to set up a service that I can use to get a message when I need it? I am solving an optimization problem 2 times a second and even though the messages are published very quickly I want to grab the most recent message just before I solve the next optimization
Comment by huckl3b3rry87 on 2017-08-01:
I would be worried that if I try to use a global variable that when I am trying to update the next optimization with the "current" variables, that they might be "updated" at the same time. It just seems a little dangerous