mvniekerk / tokio-cron-scheduler

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

Can't run in tokio::test ? #33

Closed killme2008 closed 1 year ago

killme2008 commented 1 year ago

I wrote a test case:

    #[tokio::test]
    async fn test_schedule() {
        let scheduler = JobScheduler::new().await.unwrap();
        scheduler.add(Job::new_async("*/1  * * * * *", |_, _| Box::pin( async {
            info!("Run every seconds");
        })).unwrap()).await;

        scheduler.start().await.unwrap();

        tokio::time::sleep(core::time::Duration::from_secs(100)).await;
    }

The test stucks in scheduler.add(...).

Is it expected? Or how to write a testcase for scheduler.

mvniekerk commented 1 year ago

Hi @killme2008 Thank you for the report and the example. Let me have a look

mvniekerk commented 1 year ago

Hi @killme2008 Check https://github.com/mvniekerk/tokio-cron-scheduler/blob/c0eb6575d8564dac138869bfcdced43d842451f0/examples/lib.rs#L165

The secret sauce is to add (flavor = "multi_thread", worker_threads = 2) to your tokio::test.

For example:

#[cfg(test)]
mod test {
    use tokio_cron_scheduler::{Job, JobScheduler};
    use tracing::{info, Level};
    use tracing_subscriber::FmtSubscriber;

    // Needs multi_thread to test, otherwise it hangs on scheduler.add()
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    // #[tokio::test]
    async fn test_schedule() {
        let subscriber = FmtSubscriber::builder()
            .with_max_level(Level::TRACE)
            .finish();
        tracing::subscriber::set_global_default(subscriber)
            .expect("Setting default subscriber failed");

        info!("Create scheduler");
        let scheduler = JobScheduler::new().await.unwrap();
        info!("Add job");
        scheduler
            .add(
                Job::new_async("*/1  * * * * *", |_, _| {
                    Box::pin(async {
                        info!("Run every seconds");
                    })
                })
                .unwrap(),
            )
            .await
            .expect("Should be able to add a job");

        scheduler.start().await.unwrap();

        tokio::time::sleep(core::time::Duration::from_secs(20)).await;
    }
}

The above works. I've updated the README and added the example to the examples lib.

killme2008 commented 1 year ago

@mvniekerk Thank you.