Ask Your Question

Calling spinOnce inside a service callback that publishes a message

asked 2017-01-14 10:08:24 -0500

spmaniato gravatar image

I have a roscpp service callback that, upon request, does a few things and then publishes a message on a topic. Here is an oversimplified example:

void someServiceCb(std_srvs::Trigger::Request& req,
                   std_srvs::Trigger::Response& resp) {

  if (something)
    std_msgs::Empty msg;
    resp.success = true;
    ros::spinOnce();  // Do I need this? Can it cause problems?
    resp.success = false;

The intent is to get the message out as soon as possible.

  1. Do I need that ros::spinOnce() in order to get the message out as quickly as possible?
  2. Can calling ros::spinOnce() inside a service callback cause problems?
edit retag flag offensive close merge delete


Reading more carefully, I think the answer is that ros::spinOnce() does not help with "getting the message out more quickly". I would still like to know if it can cause problems though :-)

spmaniato gravatar image spmaniato  ( 2017-01-14 13:24:24 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2017-01-14 13:26:11 -0500

billy gravatar image

You don't need a call back to publish a message. It will publish at "pub.publish(msg);". As to calling ros::spin from a callabck, I have no idea what happens. I've never used in that fashion. Call backs are typically used from the main() to enter a callback when new data arrives on a subscribed topic.

edit flag offensive delete link more


Thanks @billy. I've been doing some tests and comparing against the docs. It looks like on certain occasions calling ros::spinOnce() might be a problem (as it takes us back to the callback queue). Will try to formulate a full answer later today.

spmaniato gravatar image spmaniato  ( 2017-01-14 14:14:23 -0500 )edit

Yep; calling publish puts the message in a transmit queue, where it's picked up and sent by a background thread that isn't tied to spinOnce.

ahendrix gravatar image ahendrix  ( 2017-01-14 22:01:33 -0500 )edit

spinOnce does process message and service callbacks, so if there's another pending service request it can cause your service callback to be called a second time, from within the spinOnce in the first service callback.

ahendrix gravatar image ahendrix  ( 2017-01-14 22:02:14 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools



Asked: 2017-01-14 10:08:24 -0500

Seen: 544 times

Last updated: Jan 14 '17