How do I publish exactly one message in ROS2?

asked 2022-07-11 06:55:46 -0500

cjoshi17 gravatar image

Hello,

I am using ROS2 Galactic with Ubuntu 20.04 and C++. I want to know how to publish a message only when I get some data in a callback. For example, I want to only calculate paths when I get start and end goals and the path should be only published once. With the current tutorials on ROS2 documentation, the publisher will keep publishing paths. I want to know how I can publish only once through code. I can create an if condition and make it false once I publish a message but I think there will be some option by default.

Thank you.

edit retag flag offensive close merge delete

Comments

3

If you want to be able to control when something happens, how often it happens, under which conditions and for whom, then a topic (and publish-subscribe) doesn't sound like it would be a suitable interaction pattern.

Have you considered using a service or action instead?

gvdhoorn gravatar image gvdhoorn  ( 2022-07-11 07:48:53 -0500 )edit

Hi, thanks for answering. I guess a service call will do because I don't need to call it that often. But I would still want to know how to publish something only once or when I want it to publish. I think in ROS1 by default a publisher only publishes once but in ROS2 I think it is by default a continuous publisher. Thanks.

cjoshi17 gravatar image cjoshi17  ( 2022-07-11 23:09:55 -0500 )edit

A scenario where I need to publish exactly once is I only want to publish when I receive some data in a callback. With the wall timer, it will keep publishing the data and I don't want that. If you can add the --once tag while publishing through the terminal I believe there should be some provision provided while publishing using code. Thanks again.

cjoshi17 gravatar image cjoshi17  ( 2022-07-12 06:05:21 -0500 )edit