1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#![warn(missing_docs)]
#![allow(dead_code)]
mod time;
pub use time::Timer;
#[cfg(test)]
mod tests {
use std::sync::{atomic::AtomicUsize, Arc};
use std::sync::atomic::Ordering::SeqCst;
use std::time::Duration;
use super::*;
#[test]
fn set_timeout() {
let timer = Timer::new();
let count = Arc::new(AtomicUsize::new(0));
let count_clone = count.clone();
let _ = timer.set_timeout(
move || {
count_clone.fetch_add(1, SeqCst);
println!("run callback success");
},
Duration::from_secs(1),
);
std::thread::sleep(Duration::from_secs(1) + Duration::from_millis(20));
assert_eq!(count.load(SeqCst), 1);
}
#[test]
fn set_timeout_multi() {
let timer = Timer::new();
let count = Arc::new(AtomicUsize::new(0));
let count_clone1 = count.clone();
let _ = timer.set_timeout(
move || {
count_clone1.fetch_add(1, SeqCst);
println!("run callback success");
},
Duration::from_secs(1),
);
let count_clone2 = count.clone();
let _ = timer.set_timeout(
move || {
count_clone2.fetch_add(1, SeqCst);
println!("run callback success");
},
Duration::from_secs(1),
);
std::thread::sleep(Duration::from_secs(1) + Duration::from_millis(20));
assert_eq!(count.load(SeqCst), 2);
}
#[test]
fn cancel_timeout() {
let timer = Timer::new();
let count = Arc::new(AtomicUsize::new(0));
let count_clone = count.clone();
let cancel_timeout = timer.set_timeout(
move || {
count_clone.fetch_add(1, SeqCst);
println!("run callback success");
},
Duration::from_secs(1),
);
std::thread::sleep(Duration::from_millis(20));
cancel_timeout();
std::thread::sleep(Duration::from_secs(1));
assert_eq!(count.load(SeqCst), 0);
}
}