5
5
use rclrs:: { create_node, Context , Node , RclrsError , Timer } ;
6
6
use std:: {
7
7
env,
8
- sync:: { Arc , Mutex } ,
8
+ sync:: Arc ,
9
+ time:: Duration ,
9
10
} ;
10
11
11
12
/// Contains both the node and timer.
12
13
struct SimpleTimerNode {
13
14
node : Arc < Node > ,
15
+ #[ allow( unused) ]
14
16
timer : Arc < Timer > ,
15
17
}
16
18
@@ -20,29 +22,25 @@ impl SimpleTimerNode {
20
22
/// The callback will simply print to stdout:
21
23
/// "Drinking 🧉 for the xth time every p nanoseconds."
22
24
/// where x is the iteration callback counter and p is the period of the timer.
23
- fn new ( context : & Context , timer_period_ns : i64 ) -> Result < Self , RclrsError > {
25
+ fn new ( context : & Context , timer_period : Duration ) -> Result < Self , RclrsError > {
24
26
let node = create_node ( context, "simple_timer_node" ) ?;
25
- let count: Arc < Mutex < i32 > > = Arc :: new ( Mutex :: new ( 0 ) ) ;
26
- let timer = node. create_timer (
27
- timer_period_ns,
28
- context,
29
- Some ( Box :: new ( move |_| {
30
- let x = * count. lock ( ) . unwrap ( ) ;
27
+ let mut x = 0 ;
28
+ let timer = node. create_timer_repeating (
29
+ timer_period,
30
+ move || {
31
+ x += 1 ;
31
32
println ! (
32
- "Drinking 🧉 for the {}th time every {} nanoseconds ." ,
33
- x , timer_period_ns
33
+ "Drinking 🧉 for the {x }th time every {:?} ." ,
34
+ timer_period ,
34
35
) ;
35
- * count. lock ( ) . unwrap ( ) = x + 1 ;
36
- } ) ) ,
37
- None ,
36
+ } ,
38
37
) ?;
39
38
Ok ( Self { node, timer } )
40
39
}
41
40
}
42
41
43
42
fn main ( ) -> Result < ( ) , RclrsError > {
44
- let timer_period: i64 = 1e9 as i64 ; // 1 seconds.
45
43
let context = Context :: new ( env:: args ( ) ) . unwrap ( ) ;
46
- let simple_timer_node = Arc :: new ( SimpleTimerNode :: new ( & context, timer_period ) . unwrap ( ) ) ;
44
+ let simple_timer_node = Arc :: new ( SimpleTimerNode :: new ( & context, Duration :: from_secs ( 1 ) ) . unwrap ( ) ) ;
47
45
rclrs:: spin ( simple_timer_node. node . clone ( ) )
48
46
}
0 commit comments