veilid_tools/
process_watchdog.rs1#![cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
2
3use super::*;
4use std::sync::mpsc;
5
6pub struct ProcessWatchdog {
14 _stop: mpsc::Sender<()>,
15}
16
17impl ProcessWatchdog {
18 #[must_use]
21 pub fn start(
22 period_ms: u64,
23 late_threshold_ms: u64,
24 on_late: impl Fn(u64, u64) + Send + 'static,
25 ) -> Self {
26 let (stop, wake) = mpsc::channel::<()>();
27 let period = Duration::from_millis(period_ms);
28 let late_threshold_us = late_threshold_ms * 1000;
29 let thread = std::thread::Builder::new()
30 .name("veilid-watchdog".to_owned())
31 .spawn(move || loop {
32 let before = get_raw_timestamp();
33 match wake.recv_timeout(period) {
34 Err(mpsc::RecvTimeoutError::Timeout) => {}
35 Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => break,
36 }
37 let now = get_raw_timestamp();
38 let late_us = now.saturating_sub(before).saturating_sub(period_ms * 1000);
39 if late_us >= late_threshold_us {
40 on_late(late_us, now);
41 }
42 });
43 match thread {
44 Ok(_) => debug!("process watchdog started: period {}ms", period_ms),
45 Err(e) => warn!("process watchdog thread not started: {}", e),
46 }
47 Self { _stop: stop }
48 }
49}