-
Notifications
You must be signed in to change notification settings - Fork 188
/
Copy pathpause_and_resume.rs
112 lines (90 loc) · 3.27 KB
/
pause_and_resume.rs
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
//! An advanced example showing how to pause/resume/stop an `Engine` via an MPSC channel.
#[cfg(feature = "unchecked")]
fn main() {
panic!("This example does not run under 'unchecked'.");
}
use rhai::{Dynamic, Engine};
#[cfg(feature = "sync")]
use std::sync::Mutex;
#[cfg(not(feature = "unchecked"))]
fn main() {
let (tx, rx) = std::sync::mpsc::channel::<String>();
#[cfg(feature = "sync")]
let rx = Mutex::new(rx);
// Spawn thread with Engine, capturing the channel
std::thread::spawn(move || {
// Create Engine
let mut engine = Engine::new();
engine.on_progress(move |_ops| {
#[cfg(feature = "sync")]
if _ops % 5 != 0 {
return None;
}
#[cfg(feature = "sync")]
let rx = &*rx.lock().unwrap();
let mut paused = false;
loop {
match rx.try_recv() {
Ok(cmd) => match cmd.as_str() {
"pause" => {
println!("[Thread] Script paused. Type 'resume' to continue or 'stop' to terminate.");
paused = true;
}
"resume" => {
println!("[Thread] Resuming script...");
return None;
}
"stop" => {
println!("[Thread] Stopping script...");
return Some(Dynamic::UNIT);
}
cmd if paused => {
println!("[Thread] I don't understand '{cmd}'!");
println!("Type 'resume' to continue script, or 'stop' to terminate!");
}
_ => {
println!("[Thread] I don't understand '{cmd}'!");
return None;
}
},
Err(_) if paused => (),
Err(_) => return None,
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
});
// Run script
let _ = engine
.run(
r#"
let counter = 0;
loop {
print("[Script] One Potato...");
sleep(1);
counter += 1;
print("[Script] Two Potatoes...");
sleep(1);
print(`[Script] Boring Counter: ${counter}...`);
sleep(1);
print("[Script] Three Potatoes...");
sleep(1);
}
"#,
)
.expect_err("Error expected");
println!("[Thread] Script stopped!");
});
println!("[Main] Type 'pause' or 'stop' to control the script.");
let mut input = String::new();
loop {
input.clear();
match std::io::stdin().read_line(&mut input) {
Ok(0) => (),
Ok(_) => match tx.send(input.trim().to_string()) {
Ok(_) => (),
Err(_) => break,
},
Err(_) => break,
}
}
}