#shutdown-signal #exit #branch #tokio #running #part #gracefully

shutdown

shutdown can be used to gracefully exit (part of) a running program

8 releases

0.4.1 Jul 5, 2024
0.4.0 Jul 4, 2024
0.3.1 Sep 26, 2023
0.2.1 Dec 14, 2021
0.1.1 Dec 1, 2020

#435 in Asynchronous

Download history 108/week @ 2024-07-21 45/week @ 2024-07-28 142/week @ 2024-08-04 130/week @ 2024-08-11 160/week @ 2024-08-18 185/week @ 2024-08-25 141/week @ 2024-09-01 270/week @ 2024-09-08 373/week @ 2024-09-15 385/week @ 2024-09-22 331/week @ 2024-09-29 100/week @ 2024-10-06 259/week @ 2024-10-13 542/week @ 2024-10-20 354/week @ 2024-10-27 253/week @ 2024-11-03

1,418 downloads per month
Used in blobnet

MIT/Apache

17KB
185 lines

shutdown

shutdown can be used to gracefully exit (part of) a running program

Build Status Crates.io Documentation License

Example

The example below shows how to create a new shutdown object, create a few branches, subscribe some listeners and signal one of the branches:

use shutdown::Shutdown;

fn main() {
    let root = Shutdown::new().unwrap();

    // Create two new branches.
    let branch1 = root.branch();
    let branch2 = root.branch();

    // Create two new subscribers to the first branch.
    let subscriber1 = branch1.subscribe();
    let subscriber2 = branch1.subscribe();

    // Signal the first branch.
    branch1.signal();
}

Usage

Add shutdown and Tokio to your dependencies:

shutdown = "0.4"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

And then get started in your main.rs:

use shutdown::Shutdown;
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    let mut root = Shutdown::new().unwrap();

    while !root.is_signalled() {
        // Wait for a task to finish while also
        // listening for any shutdown signals.
        tokio::select! {
            _ = sleep(Duration::from_secs(30)) => (),
            _ = root.received() => break,
        }

        // Subscribe and spawn a long running task which will
        // end its loop when a shutdown signal is received.
        let shutdown = root.subscribe();
        tokio::spawn(async move {
            while !shutdown.is_signalled() {
                // Do stuff until we're shutdown...
            }
        })
    }
}

Running the tests

Because each "root" shutdown object registers itself to listen for SIGINT and SIGTERM signals, the test need to run one by one. So to run the tests, please execute:

$ cargo test -- --test-threads=1

Contributions

Pull requests and issues are always welcome and appreciated!

License

shutdown is distributed under the terms of both the MIT license and the Apache License (Version 2.0)

Dependencies

~4–11MB
~115K SLoC