Crates.io | periodically |
lib.rs | periodically |
version | 0.2.0 |
source | src |
created_at | 2024-08-17 16:26:43.116555 |
updated_at | 2024-08-24 21:16:36.074987 |
description | A library for running tasks on a schedule |
homepage | |
repository | https://github.com/DavidCollard/periodically |
max_upload_size | |
id | 1341820 |
size | 35,717 |
Periodically
provides a robust and ergonomic library for writing periodic or scheduled jobs in Rust.
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.