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

build shutdown

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

6 releases

0.3.1 Sep 26, 2023
0.3.0 Sep 26, 2023
0.2.1 Dec 14, 2021
0.2.0 Aug 31, 2021
0.1.1 Dec 1, 2020

#209 in Build Utils

Download history 104/week @ 2023-12-04 121/week @ 2023-12-11 79/week @ 2023-12-18 47/week @ 2023-12-25 19/week @ 2024-01-01 87/week @ 2024-01-08 41/week @ 2024-01-15 72/week @ 2024-01-22 55/week @ 2024-01-29 27/week @ 2024-02-05 102/week @ 2024-02-12 81/week @ 2024-02-19 81/week @ 2024-02-26 123/week @ 2024-03-04 248/week @ 2024-03-11 91/week @ 2024-03-18

546 downloads per month
Used in blobnet

MIT/Apache

15KB
167 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 signal, 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.3"
tokio = { version = "1", features = ["full"] }

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 signal 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–14MB
~134K SLoC