Skip to main content

worker_loop/
worker_loop.rs

1use std::{error::Error, thread, time::Duration};
2
3use beatwise::{Monitor, StoppedError, TaskConfig, Timing};
4
5fn main() -> Result<(), Box<dyn Error>> {
6    let monitor = Monitor::new();
7    let heartbeat = monitor.register(
8        TaskConfig::new("worker-loop", Timing::fixed(Duration::from_millis(250)))
9            .with_startup_grace(Duration::from_secs(1)),
10    )?;
11    let task_id = heartbeat.id();
12
13    let worker = thread::spawn(move || -> Result<(), StoppedError> {
14        for completed_step in 1..=3 {
15            thread::sleep(Duration::from_millis(50));
16            heartbeat.beat()?;
17            println!("worker completed step {completed_step}");
18        }
19
20        // Dropping the final heartbeat at the end of this closure marks the
21        // retained task record as stopped.
22        Ok(())
23    });
24
25    while !worker.is_finished() {
26        thread::sleep(Duration::from_millis(25));
27        if let Some(status) = monitor.status(task_id) {
28            println!("observer: {:?}", status.health);
29        }
30    }
31
32    worker.join().expect("worker thread panicked")?;
33
34    let stopped = monitor
35        .status(task_id)
36        .expect("stopped task remains retained until purged");
37    println!("after join: {:?}", stopped.health);
38
39    assert_eq!(monitor.purge_stopped(), 1);
40    assert!(monitor.status(task_id).is_none());
41
42    Ok(())
43}