mvniekerk / tokio-cron-scheduler

Schedule tasks on Tokio using cron-like annotation
Apache License 2.0
519 stars 60 forks source link

[Maybe Non-issue] JobScheduler::shutdown_on_ctrl_c does not run the shutdown handler #76

Closed AregevDev closed 2 months ago

AregevDev commented 2 months ago

Hello, I enjoy using tokio-cron-scheduler However, I am trying to implement a graceful shutdown mechanism that handles the ctrl_c signal. I have this simple example

use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use log::{info, warn};
use tokio::io::AsyncWriteExt;
use tokio::signal::ctrl_c;
use tokio::task::JoinSet;
use tokio_cron_scheduler::{Job, JobScheduler};
use tokio_util::sync::CancellationToken;

#[tokio::main]
async fn main() {
    simple_logger::init().unwrap();

    let token0 = CancellationToken::new();
    let token1 = token0.clone();

    let mut sched = JobScheduler::new().await.unwrap();
    sched.shutdown_on_ctrl_c();
    sched.set_shutdown_handler(Box::new(move || {
        Box::pin({
            let value = token1.clone();
            async move {
                warn!("Scheduler shut down.");
                value.cancel();
            }
        })
    }));

    static COUNTER: AtomicUsize = AtomicUsize::new(2);

    let job = Job::new_async("1/2 * * * * *", |_uuid, mut _lock| Box::pin( async move {
        let i = COUNTER.load(Ordering::SeqCst);
        match i {
            0 => {
                info!("Shutting down");
                _lock.shutdown().await.unwrap();
                return;
            }
            _ => {
                COUNTER.fetch_sub(1, Ordering::SeqCst);
            }
        }
        println!("{}", i);
    })).unwrap();

    sched.add(job).await.unwrap();
    sched.start().await.unwrap();

    token0.cancelled().await;

    info!("All Tasks finished.")
}

When signaling Ctrl-C, the scheduler shuts down (it doesn't print numbers anymore) but the handler code doesn't get run. "Scheduler shut down." isn't printed. Am I missing something?

AregevDev commented 2 months ago

shutdown_on_ctrl_c clones the Scheduler instance. If you call it before the shutdown handler, the handlee won't get registered.