Skip to content

Commit

Permalink
Make timers context-aware. (#1296)
Browse files Browse the repository at this point in the history
This should make it easier to create examples and demos
that properly clean up after themselves.

Signed-off-by: Chris Lalancette <[email protected]>
  • Loading branch information
clalancette authored Jun 5, 2024
1 parent 88ce194 commit 8db266a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
13 changes: 13 additions & 0 deletions rclpy/rclpy/timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@

import threading

from types import TracebackType
from typing import Callable
from typing import Optional
from typing import Type

from rclpy.callback_groups import CallbackGroup
from rclpy.clock import Clock
Expand Down Expand Up @@ -114,6 +116,17 @@ def time_until_next_call(self):
with self.__timer:
return self.__timer.time_until_next_call()

def __enter__(self) -> 'Timer':
return self

def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
self.destroy()


class Rate:
"""A utility for sleeping at a fixed rate."""
Expand Down
16 changes: 16 additions & 0 deletions rclpy/test/test_timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,3 +202,19 @@ def test_timer_without_autostart():
if node is not None:
node.destroy_node()
rclpy.shutdown()


def test_timer_context_manager():
rclpy.init()
try:
with rclpy.create_node('test_timer_without_autostart') as node:
with node.create_timer(1, lambda: None, autostart=False) as timer:
assert timer.is_canceled()

timer.reset()
assert not timer.is_canceled()

timer.cancel()
assert timer.is_canceled()
finally:
rclpy.shutdown()

0 comments on commit 8db266a

Please sign in to comment.