Tokio panics during shutdown

If the runtime has been shut down

If the Handle’s associated Runtime has been shut down (through Runtime::shutdown_background, Runtime::shutdown_timeout, or by dropping it) and Handle::block_on is used it might return an error or panic. Specifically IO resources will return an error and timers will panic. Runtime independent futures will run as normal.

src: Handle in tokio::runtime - Rust

A solution can be

use tokio::{runtime::Runtime, signal};
use tokio_schedule::{every, Job};

fn main() {
    let runtime = Runtime::new().unwrap();

    let job1 = every(3).seconds().perform(|| async {
        // do some work
        println!("3s scheduled execution");
    });

    let job2 = every(2).seconds().perform(|| async {
        // do some work
        println!("2s scheduled execution");
    });

    let ctrl_c_handle = async move {
        let _ = signal::ctrl_c().await;
    };

    let ctrl_c = runtime.block_on(async {
        tokio::select! {
            _ = job1 => false,
            _ = job2 => false,
            _ = ctrl_c_handle => true,
        }
    });
    if ctrl_c {
        println!("Program exit due to ctrl_c!")
    }
}
2 Likes