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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
///
pub mod impl_timer {
use std::sync::{Arc, Mutex};
/// start_time:Instant,step_time:Duration,stop_time:Duration,func:Box<dyn Fn()>
/// ```rust
/// use doe::run_timer;
/// fn run(){
/// println!("running ");
///}
/// run_timer(std::time::Instant::now(),std::time::Duration::from_secs(1),std::time::Duration::from_secs(5),Box::new(run));
///
/// ```
pub fn run_timer(
start_time: std::time::Instant,
step_time: std::time::Duration,
stop_time: std::time::Duration,
func: Box<dyn Fn()>,
) {
let mut elapsed_time = std::time::Duration::new(0, 0);
while elapsed_time < stop_time {
func();
std::thread::sleep(step_time);
elapsed_time = start_time.elapsed();
}
}
/// run timer by shared state
/// ```rust
/// use std::sync::{Arc, Mutex};
/// use doe::*;
/// let run_state = Arc::new(Mutex::new(true));
/// let t1 = std::thread::spawn({
/// let run_state = Arc::clone(&run_state);
/// move || {
/// std::thread::sleep(std::time::Duration::from_secs(5));
/// *run_state.lock().unwrap() = false;
/// }
/// });
///
/// let t2 = std::thread::spawn({
/// let run_state = Arc::clone(&run_state);
/// move || {
/// run_timer_by_state(
/// std::time::Duration::from_secs(1),
/// run_state,
/// Box::new(|| {
/// // Function body goes here
/// println!("Running...");
/// }),
/// );
/// }
/// });
///
/// // Wait for the threads to finish
/// t1.join().expect("Thread panicked");
/// t2.join().expect("Thread panicked");
///
/// ```
pub fn run_timer_by_state(
step_time: std::time::Duration,
run_state: Arc<Mutex<bool>>,
func: Box<dyn Fn()>,
) {
loop {
if *run_state.lock().unwrap() {
std::thread::sleep(step_time);
func();
} else {
break;
}
}
}
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
/// run timer by send stop_massge by channel
///```rust
///use std::sync::mpsc;
///use std::thread;
///use std::time::Duration;
///use doe::*;
/// let (sender, receiver) = mpsc::channel::<bool>();
/// let t1 = thread::spawn(move || {
/// thread::sleep(Duration::from_secs(5));
/// sender.send(true).unwrap();
/// });
/// let t2 = thread::spawn(move || {
/// run_timer_by_channel(Duration::from_secs(1), receiver, Box::new(|| {
/// println!("running..");
/// }));
/// });
/// t1.join().expect("Thread panicked");
/// t2.join().expect("Thread panicked");
/// ```
pub fn run_timer_by_channel(
step_time: Duration,
stop_message: mpsc::Receiver<bool>,
func: Box<dyn Fn() + Send>,
) {
loop {
match stop_message.try_recv() {
Ok(true) => break,
_ => {
thread::sleep(step_time);
func();
}
}
}
}
}