创建定时器
self.timer = self.create_timer(1.0, self.callback)
函数定义
def create_timer(self,timer_period_sec: float,callback: Callable,callback_group: CallbackGroup = None,clock: Clock = None,) -> Timer:
timer_period_sec: 定时执行时间间隔(s)
callback: 回调函数
callback_group: 定时器的回调组,默认值None
clock: 计时器时钟源,默认值None
回调函数
def callback(self):print("Callback function called")
取消定时器
self.timer.cancel()
完整代码
import rclpy
from rclpy.node import Nodeclass MyNode(Node):def __init__(self):super().__init__('my_node')# 创建定时器self.timer = self.create_timer(1.0, self.callback)def callback(self):print("Callback function called")def cancel_timer(self):if self.timer is not None and self.get_logger() is not None:self.get_logger().info("Cancelling timer...")# 取消定时器self.timer.cancel()self.timer = Nonedef main():rclpy.init()node = MyNode()try:rclpy.spin(node)except KeyboardInterrupt:passfinally:node.destroy_node()rclpy.shutdown()if __name__ == '__main__':main()