2 unstable releases

0.2.0 Aug 24, 2024
0.1.0 Aug 17, 2024

#343 in Concurrency

Custom license

29KB
399 lines

Periodically

Periodically provides a robust and ergonomic library for writing periodic or scheduled jobs in Rust.

Documentation

Crates.io MIT licensed

Quick example

It is easy to write a task definition:

struct MyTask;

impl Task for MyTask {
    fn run(&self) {
        println!("MyTask is running");
    }
}

and then plug it into a scheduler using Periodically's provided schedules:

fn main() {
    /// Create a scheduler using a tokio runtime, or provide your own
    let runtime = tokio::runtime::Runtime::new().unwrap();
    let mut scheduler = Scheduler::tokio_scheduler(runtime);

    /// the task begins running once a second
    let id = scheduler.add_sync_task(MyTask, IntervalSchedule::every(Duration::from_secs(1)));

    /// the task stops running
    scheduler
        .stop_task(id)
        .expect("Should not err for a known identifier");
}

or, define your own schedule if needed:

pub struct OneShot {
    delay: Duration,
}

impl<T> Schedule<T> for OneShot {
    fn initial(&self) -> Option<std::time::Duration> {
        Some(self.delay)
    }

    fn next(&self, _: T) -> Option<std::time::Duration> {
        None
    }
}

More interactive examples can be found here.

Dependencies

~2–8.5MB
~64K SLoC