4 releases

0.1.3 May 16, 2024
0.1.2 May 17, 2023
0.1.1 Apr 4, 2023
0.1.0 Apr 4, 2023

#13 in #cron-scheduler

Download history 211/week @ 2024-11-20 229/week @ 2024-11-27 322/week @ 2024-12-04 215/week @ 2024-12-11 116/week @ 2024-12-18 60/week @ 2024-12-25 237/week @ 2025-01-01 288/week @ 2025-01-08 235/week @ 2025-01-15 398/week @ 2025-01-22 366/week @ 2025-01-29 429/week @ 2025-02-05 499/week @ 2025-02-12 241/week @ 2025-02-19 314/week @ 2025-02-26 218/week @ 2025-03-05

1,334 downloads per month
Used in rjob

MIT license

18KB
320 lines

GitHub Contributors Stars Build Status Downloads Crates.io

tokio-cron

tokio-cron is a simple cron-scheduler built on Tokio.

Why you might use it compared to alternatives:

  • It's roughly 200 lines of code and minimal dependencies
  • It has support for tracing

Here is a comprehensive example:

use tokio_cron::{Scheduler, Job, daily};
use std::sync::atomic::{AtomicUsize, Ordering};

async fn simple_async_fn() {
    println!("Hello, world!");
}

async fn async_fn_with_args(counter: Arc<AtomicUsize>) {
    println!("Hello, world!");
}

#[tokio::main]
async fn main() {
    // You can use a local (timezone) scheduler, or a UTC scheduler.
    let mut scheduler = Scheduler::local();
    
    // This counter is to show data sharing in action. It's not required.
    // In a real environment, this might be a database connection pool, or other application state.
    let counter = Arc::new(AtomicUsize::new(0));

    // Add an async closure:
    // Run a named job "increase-counter" every day at 8am.
    let c = counter.clone();
    scheduler.add(Job::named("increase-counter", daily("8"), move || {
        let counter = c.clone();
        async move {
            counter.fetch_add(1, Ordering::SeqCst);
            println!("Hello, world!");
        }
    }));

    // Add a sync task:
    scheduler.add(Job::new_sync("*/1 * * * * *", move || {
        println!("Hello, world!");
    }));

    // Add a simple async function:
    scheduler.add(Job::new("*/1 * * * * *", simple_async_fn));
    
    // Add an async function with arguments:
    let c = counter.clone();
    scheduler.add(Job::new("*/2 * * * * *", move || {
        async_fn_with_args(c.clone())
    }));
    
    tokio::time::sleep(std::time::Duration::from_secs(3)).await;
    
    let result = counter.clone().load(Ordering::SeqCst);
    println!("Counter: {}", result);
}

See tests in src/lib.rs for other examples and usage.

Dependencies

~5–12MB
~124K SLoC