| Crates.io | async-periodic-job |
| lib.rs | async-periodic-job |
| version | 0.1.3 |
| created_at | 2025-09-06 10:51:54.61575+00 |
| updated_at | 2025-09-07 03:02:04.304553+00 |
| description | A simple async periodic job scheduler library base on tokio-util. |
| homepage | |
| repository | https://github.com/imstevez/async-periodic-job |
| max_upload_size | |
| id | 1826948 |
| size | 24,364 |
A simple async periodic job scheduler library base on tokio-util.
Ctrl+C signal or a cancellation token[dependencies]
async-periodic-job = "0.1.3"
use async_periodic_job::{Job, Scheduler};
use std::time::Duration;
// Define a job without options
struct JobImplA;
impl Job for JobImplA {
async fn run(&mut self) {
// ...
}
}
// Define a job with customized period and time truncation
struct JobImplB;
impl Job for JobImplB {
// Job repeat period, default: 1s
fn period(&self) -> Duration {
Duration::from_secs(2)
}
// If run job with truncate time, default: true
fn with_truncate_time(&self) -> bool {
false
}
// Job run
async fn run(&mut self) {
// ...
}
}
#[tokio::main]
async fn main() {
// Spawn job instances of JobA and JobB and wait scheduler stop
// When received `CTRL+C` signal, scheduler will exit (after all running jobs exit)
Scheduler::new()
.spawn(JobImplA)
.spawn(JobImplB)
.wait()
.await;
}
use async_periodic_job::{Job, Scheduler, Token};
use std::time::Duration;
use tokio::time::sleep;
// Define a job with cancel
struct JobImpl;
impl Job for JobImpl {
async fn run(&mut self) {
// ...
}
}
#[tokio::main]
async fn main() {
// Create a cancellation token and spawn a future to cancel the token after 5 secs
let token = Token::new();
let token_copy = token.clone();
tokio::spawn(async move {
sleep(Duration::from_secs(5)).await;
token_copy.cancel();
});
// Spawn instance of JobImpl and wait scheduler stop
// When token cancelled, scheduler will exit (after all running jobs exit)
Scheduler::new()
.spawn(JobImpl)
.wait_cancel(token)
.await;
}
use async_periodic_job::{Job, Scheduler, Token};
// Define a job with cancel
struct JobImpl;
impl Job for JobImpl {
// If run job with cancel, default: false
// When this method returned true, job method `run_with_cancel` will be executed instead of `run`
fn with_with_cancel(&self) -> bool {
true
}
// Job run: instead implementing `run`, implement `run_with_cancel`
async fn run_with_cancel(&mut self, token: Token) {
loop {
if token.is_cancelled() {
return;
}
// ...
}
}
}
#[tokio::main]
async fn main() {
Scheduler::new()
.spawn(JobImpl)
.wait()
.await;
}
MIT
Contributions and suggestions are welcome!