timeout/
timeout.rs

1use std::{
2    sync::{atomic::AtomicUsize, Arc},
3    time::Duration,
4};
5
6use std::sync::atomic::Ordering::SeqCst;
7
8use swnb_timer::Timer;
9
10fn sleep(duration: Duration) {
11    std::thread::sleep(duration);
12}
13
14fn main() {
15    let timer = Timer::new();
16    let count = Arc::new(AtomicUsize::new(0));
17    let count_clone = count.clone();
18    // count will increase after 1 sec
19    let _ = timer.set_timeout(
20        move || {
21            count_clone.fetch_add(1, SeqCst);
22            println!("run callback success");
23        },
24        Duration::from_secs(1),
25    );
26
27    sleep(Duration::from_secs(1) + Duration::from_millis(20));
28
29    assert_eq!(count.load(SeqCst), 1);
30
31    let count_clone = count.clone();
32    let cancel_timeout = timer.set_timeout(
33        move || {
34            count_clone.fetch_add(1, SeqCst);
35            println!("run callback success");
36        },
37        Duration::from_secs(1),
38    );
39
40    sleep(Duration::from_millis(20));
41    // cancel callback;
42    cancel_timeout();
43    sleep(Duration::from_secs(1));
44    // count still be 1;
45    assert_eq!(count.load(SeqCst), 1);
46}