Skip to content

Commit f77d593

Browse files
committed
Update timer example
Signed-off-by: Michael X. Grey <[email protected]>
1 parent d5c3e71 commit f77d593

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed

examples/rclrs_timer_demo/src/rclrs_timer_demo.rs

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,14 @@
55
use rclrs::{create_node, Context, Node, RclrsError, Timer};
66
use std::{
77
env,
8-
sync::{Arc, Mutex},
8+
sync::Arc,
9+
time::Duration,
910
};
1011

1112
/// Contains both the node and timer.
1213
struct SimpleTimerNode {
1314
node: Arc<Node>,
15+
#[allow(unused)]
1416
timer: Arc<Timer>,
1517
}
1618

@@ -20,29 +22,25 @@ impl SimpleTimerNode {
2022
/// The callback will simply print to stdout:
2123
/// "Drinking 🧉 for the xth time every p nanoseconds."
2224
/// 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> {
2426
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;
3132
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,
3435
);
35-
*count.lock().unwrap() = x + 1;
36-
})),
37-
None,
36+
},
3837
)?;
3938
Ok(Self { node, timer })
4039
}
4140
}
4241

4342
fn main() -> Result<(), RclrsError> {
44-
let timer_period: i64 = 1e9 as i64; // 1 seconds.
4543
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());
4745
rclrs::spin(simple_timer_node.node.clone())
4846
}

0 commit comments

Comments
 (0)