# What is rospy.spin(), ros::spin(), ros::spinOnce(), and what are they for?

**URL:** <https://get-help.theconstruct.ai/t/what-is-rospy-spin-ros-spin-ros-spinonce-and-what-are-they-for/58>\
**Category:** Knowledgebase\
**Tags:** rospy, roscpp\
**Created:** [July 18, 2019, 2:57pm UTC](https://get-help.theconstruct.ai/t/what-is-rospy-spin-ros-spin-ros-spinonce-and-what-are-they-for/58 "2019-07-18T14:57:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bayodesegun](https://get-help.theconstruct.ai/user_avatar/get-help.theconstruct.ai/bayodesegun/32/10684_2.png) [@bayodesegun](https://get-help.theconstruct.ai/u/bayodesegun)\
**Post date:** [July 18, 2019, 2:57pm UTC](https://get-help.theconstruct.ai/t/what-is-rospy-spin-ros-spin-ros-spinonce-and-what-are-they-for/58/1 "2019-07-18T14:57:47Z")

</div>

### First, let make a distinction based on the ROS API:

- `rospy.spin()` - used by ROS Python API.
- `ros::spin()` and `ros::spinOnce()` - used by ROS C++ API.

### That said, what are they for?

- They are all used in connection with subscribers.

- `rospy.spin()` and `ros::spin()` both block the main thread from exiting until ROS invokes a shutdown - via a `Ctrl + C` for example. They are written as the last line of code of the main thread of the program.

- For ROS Python, `rospy.spin()` can be replaced by a while loop, so it is not mandatory to use it when working with subscribers. The three code snippets below are equivalent as they prevent the main thread from exiting until a shutdown is requested in some way.

```auto
# setup subscribers and callbacks (and anything else)
rospy.spin()

```

```auto
while not rospy.is_shutdown():
   # do some work or nothing

```

```auto
while not ctrl_c:
   # do some work or nothing

```

- For ROS C++, `ros::spin()` is mandatory for subscribers. If you are subscribing messages, services or actions you must call `ros::spin()` to process the events. While `spinOnce()` handles the events and returns immediately, `spin()` blocks until ROS invokes a shutdown. `spinOnce()` is used where other lines of code need to be executed along with processing arriving messages.

```auto
// ros::spin()
ros::init(argc, argv, "my_node");
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe(...);
...
ros::spin();

```

```auto
// ros::spinOnce()
ros::Rate r(10); // 10 hz
while (should_continue)
{
  // ... do some work, publish some messages, etc. ...
  ros::spinOnce();
  r.sleep();
}

```

---

<div class="post-metadata">

**Author:** ![bayodesegun](https://get-help.theconstruct.ai/user_avatar/get-help.theconstruct.ai/bayodesegun/32/10684_2.png) [@bayodesegun](https://get-help.theconstruct.ai/u/bayodesegun)\
**Post date:** [January 25, 2023, 10:28am UTC](https://get-help.theconstruct.ai/t/what-is-rospy-spin-ros-spin-ros-spinonce-and-what-are-they-for/58/2 "2023-01-25T10:28:23Z")

</div>


