An asynchronous task scheduling library written in Rust
About
tasklet is a task scheduling library written in Rust. It is built over tokio runtime and utilizes green threads
in order to run tasks asynchronously.
Dependencies
| library | version |
|---|---|
| cron | 0.15.0 |
| chrono | 0.4.42 |
| log | 0.4.29 |
| tokio | 1.48.0 |
| futures | 0.3.31 |
| thiserror | 2.0.17 |
How to use this library
In your Cargo.toml add:
[dependencies]
tasklet = "0.3.1"
Upgrading from 0.2.x? See the migration notes below — task steps are now
async.
Example
Find more examples in the examples folder.
Task steps are asynchronous: every step is a closure that returns a future, so it can
.await real work (I/O, timers, network calls) without blocking the runtime.
use info;
use SimpleLogger;
use Error;
use Success;
use ;
/// A simple example of a task with two steps,
/// that might work or fail sometimes.
async
Graceful shutdown
scheduler.run() normally loops forever. To stop it cleanly, grab a
SchedulerHandle with scheduler.handle() before running and call shutdown()
from anywhere — the current round finishes, the tasks are drained and run() returns:
# use TaskScheduler;
#
# async
You can also drive the shutdown with any future via scheduler.run_until(future) — for
example a timer or an OS signal.
Timeouts, retries and lifecycle callbacks
Tasks can be made resilient with a few optional builder settings (all non-breaking, added in 0.3.1):
use Duration;
use Success;
use ;
let _task = new
.every
// Cancel any single step attempt that runs longer than this.
.timeout
// Retry failing steps with exponential backoff (100ms, 200ms, 400ms), capped at 2s.
.retry
// Async lifecycle hooks.
.on_success
.on_failure
.on_finish
.add_step
.build;
- Timeout (
.timeout) bounds each individual step attempt; a step that exceeds it is cancelled and treated as a (retryable) failure. - Retry (
.retry) re-attempts a step that returnsTaskStepStatusErr::Error(or times out). UseRetryPolicy::fixedorRetryPolicy::exponential. A step returningTaskStepStatusErr::ErrorDeletebypasses retries and removes the task immediately. - Callbacks (
.on_success/.on_failure/.on_finish) are async hooks;on_finishfires once when the task reaches a terminal state.
See examples/retry_timeout_example.rs for a runnable demo.
Migrating from 0.2.x to 0.3.0
-
Steps are now async. A step closure must return a future. Wrap synchronous bodies in an
asyncblock:// 0.2.x .add_step // 0.3.0 .add_stepFor state that changes between runs, snapshot it in the (
FnMut) closure andmovethe snapshot into theasync moveblock so the future stays'static. -
TaskGenerator::newnow returns aResult. It no longer panics on an invalid cron expression — call?/.unwrap()on the result. -
TaskScheduler::runcan now stop. It returns when a shutdown is requested through aSchedulerHandle; if you never request one, behaviour is unchanged (runs forever).
Author
Stavros Grigoriou (stav121)