Here is a page that goes into more detail. But spin() just lets all the callbacks get called for your subscribers. Your example code doesn't have a subscriber so you wouldn't need spin() in that case.
If you did setup a subscriber and didn't have spin(), your program would just start, setup subscribers, then close without the subscriber callbacks ever getting called.
But when you do have a subscriber, all of your code runs then you put a spin() at the end to keep the program from just exiting when it reaches the end of main(). Instead of exiting, a loop continuously runs to allow the callbacks to be called when a new message arrives. To be clear, ROS will not process any callback until spin() is called.
Here is a related question with great answers.
Originally posted by Airuno2L with karma: 3460 on 2017-03-20
This answer was ACCEPTED on the original site
Post score: 15
Original comments
Comment by Bill5785 on 2017-03-20:
It seems that spin
has no relationship to publishers
, right? So how do publishers continuously publish data. (It cannot run in loop like subscribers by spin)
Comment by Airuno2L on 2017-03-20:
Just run a while loop and publish. Spin is not needed for publishers since there is no callback. Its mentioned in this tutorial that it is good practice
Comment by Bill5785 on 2017-03-20:
The link doesnt exist. I read other tutorials and as far as I understand, spin
and spinOnce inside while loop
are similar except that the latter one can assign loop rate. In this case, does it mean spin
can also make publisher run continuously if there is data to publish?
Comment by Airuno2L on 2017-03-20:
sorry, having trouble editing the comment, I'm working on it.
Comment by Airuno2L on 2017-03-20:
Geez, not sure what's going on with the link, here it is in text: http://wiki.ros.org/ROS/Tutorials/WritingPublisherSubscriber(c%2B%2B)#roscpp_tutorials.2BAC8-Tutorials.2BAC8-WritingPublisherSubscriber.The_Code
Comment by Airuno2L on 2017-03-20:
Long story short, you don't need spin or spinOnce if you don't have any subscribers. Publishers don't need it because they don't use callbacks.