-
Notifications
You must be signed in to change notification settings - Fork 280
/
Copy pathos_signals.ts
39 lines (33 loc) · 1.12 KB
/
os_signals.ts
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
/**
* @title Handling OS signals
* @difficulty beginner
* @tags cli
* @run <url>
* @resource {https://docs.deno.com/api/deno/~/Deno.addSignalListener} Doc: Deno.addSignalListener
* @group System
*
* You can listen for OS signals using the `Deno.addSignalListener` function.
* This allows you to do things like gracefully shutdown a server when a
* `SIGINT` signal is received.
*/
console.log("Counting seconds...");
let i = 0;
// We isolate the signal handler function so that we can remove it later.
function sigIntHandler() {
console.log("interrupted! your number was", i);
Deno.exit();
}
// Then, we can listen for the `SIGINT` signal,
// which is sent when the user presses Ctrl+C.
Deno.addSignalListener("SIGINT", sigIntHandler);
// While we're waiting for the signal, we can do other things,
// like count seconds, or start a server.
const interval = setInterval(() => {
i++;
}, 1000);
// And, after 10 seconds, we can exit and remove the signal listener.
setTimeout(() => {
clearInterval(interval);
Deno.removeSignalListener("SIGINT", sigIntHandler);
console.log("done! it has been 10 seconds");
}, 10_000);