Skip to content

Commit 972d494

Browse files
committed
example: simplify example with tokio select
1 parent b5a549b commit 972d494

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

examples/worker.rs

+11-10
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,8 @@ async fn worker(name: u64) {
1212
let mut counter = 0;
1313
loop {
1414
let result = tokio::select! {
15-
_ = guard.wait() => None,
16-
r = do_work(name) => Some(r),
17-
};
18-
19-
let result = match result {
20-
None => break,
21-
Some(x) => x,
15+
r = do_work(name) => r,
16+
_ = guard.wait() => break,
2217
};
2318

2419
counter += result;
@@ -34,16 +29,22 @@ async fn worker(name: u64) {
3429
}
3530

3631
async fn important_worker() {
37-
let _guard = elegant_departure::get_shutdown_guard().shutdown_on_drop();
32+
let guard = elegant_departure::get_shutdown_guard().shutdown_on_drop();
3833

39-
// Do some important work.
4034
for i in 0.. {
41-
sleep(Duration::from_secs(1)).await;
35+
// Do some important work and wait for the shutdown.
36+
tokio::select! {
37+
_ = sleep(Duration::from_secs(1)) => {},
38+
_ = guard.wait() => break,
39+
};
40+
4241
if i == 5 {
4342
panic!("Oh no an unexpected crash in the important worker!");
4443
}
4544
println!("[important_worker] Did some important work");
4645
}
46+
47+
println!("[important_worker] Important worker is shutting down");
4748
}
4849

4950
#[tokio::main]

0 commit comments

Comments
 (0)