1
+ /// Creates a SimpleTimerNode, initializes a node and the timer with a callback
2
+ /// that prints the timer callback execution iteration. The callback is executed
3
+ /// thanks to the spin, which is in charge of executing the timer's events among
4
+ /// other entities' events.
5
+ use rclrs:: { create_node, Context , Node , Timer , RclrsError } ;
6
+ use std:: { env, sync:: { Arc , Mutex } } ;
7
+
8
+ /// Contains both the node and timer.
9
+ struct SimpleTimerNode {
10
+ node : Arc < Node > ,
11
+ timer : Arc < Timer > ,
12
+ }
13
+
14
+ impl SimpleTimerNode {
15
+
16
+ /// Creates a node and a timer with a callback.
17
+ ///
18
+ /// The callback will simply print to stdout:
19
+ /// "Drinking 🧉 for the <x>th time every <p> nanoseconds."
20
+ /// where <x> is the iteration callback counter and <p> is the period of the timer.
21
+ fn new ( context : & Context , timer_period_ns : i64 ) -> Result < Self , RclrsError > {
22
+ let node = create_node ( context, "simple_timer_node" ) ?;
23
+ let count: Arc < Mutex < i32 > > = Arc :: new ( Mutex :: new ( 0 ) ) ;
24
+ let timer = node. create_timer (
25
+ timer_period_ns,
26
+ context,
27
+ Some ( Box :: new ( move |_| {
28
+ let x = * count. lock ( ) . unwrap ( ) ;
29
+ println ! ( "Drinking 🧉 for the {}th time every {} nanoseconds." , x, timer_period_ns) ;
30
+ * count. lock ( ) . unwrap ( ) = x + 1 ;
31
+ } ) ) ,
32
+ None ,
33
+ ) ?;
34
+ Ok ( Self { node, timer } )
35
+ }
36
+ }
37
+
38
+
39
+ fn main ( ) -> Result < ( ) , RclrsError > {
40
+ let timer_period: i64 = 1e9 as i64 ; // 1 seconds.
41
+ let context = Context :: new ( env:: args ( ) ) . unwrap ( ) ;
42
+ let simple_timer_node = Arc :: new ( SimpleTimerNode :: new ( & context, timer_period) . unwrap ( ) ) ;
43
+ rclrs:: spin ( simple_timer_node. node . clone ( ) )
44
+ }
0 commit comments