Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Destroying the node won't exit rclpy.spin() loop. One way to implement this is by checking your node's self.running status in main loop and using rclpy.spin_once() -function. Here is a fully working example:

#!/usr/bin/env python3
import rclpy
from rclpy.node import Node


class MyNode(Node):
    def __init__(self, name):
        super().__init__(name)
        self.running = True
        self.timer = self.create_timer(0.1, self.action)

    def action(self):
        print("Callback")
        self.running = False
        self.destroy_timer(self.timer)


def main(args=None):
    rclpy.init(args=args)

    my_node = MyNode("my_node")
    while my_node.running and rclpy.ok():
        try:
            rclpy.spin_once(my_node)
        except KeyboardInterrupt:
            break

    my_node.destroy_node()
    print("Shutting down rclpy")
    rclpy.shutdown()


if __name__ == '__main__':
    main()