Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "tasklet"
version = "0.4.0"
version = "0.4.1"
authors = ["Stavros Grigoriou <unix121@protonmail.com>"]
edition = "2021"
rust-version = "1.90.0"
Expand Down
41 changes: 39 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,15 @@ In your `Cargo.toml` add:

```
[dependencies]
tasklet = "0.4.0"
tasklet = "0.4.1"
```

To derive `serde` on the observable state types (`TaskState`, `Status`, `RunRecord`,
`StepState`, ...) for a control plane or API, enable the optional `serde` feature:

```
[dependencies]
tasklet = { version = "0.4.0", features = ["serde"] }
tasklet = { version = "0.4.1", features = ["serde"] }
```

> **Upgrading from 0.2.x?** See the [migration notes](#migrating-from-02x-to-030) below —
Expand Down Expand Up @@ -211,6 +211,43 @@ for state in handle.statuses() {

See [`examples/overlap_and_status_example.rs`](/examples/overlap_and_status_example.rs) for a runnable demo.

Since 0.4.1, `handle.step_states(id)` reflects step transitions *live* during a run, not
only after it finishes: a completed early step shows as `Succeeded` while a later step is
still `Pending`.

## Schedule helpers

Since 0.4.1 you can express common cadences without writing cron by hand. Each helper is a
thin wrapper over `every(...)`:

```rust,no_run
# use tasklet::TaskBuilder;
let _ = TaskBuilder::new(chrono::Local).every_seconds(5); // "*/5 * * * * * *"
let _ = TaskBuilder::new(chrono::Local).every_minutes(15); // "0 */15 * * * * *"
let _ = TaskBuilder::new(chrono::Local).every_hours(6); // "0 0 */6 * * * *"
let _ = TaskBuilder::new(chrono::Local).hourly_at(15); // minute 15 of every hour
let _ = TaskBuilder::new(chrono::Local).daily_at(9, 30); // every day at 09:30
```

Out-of-range values (e.g. `every_seconds(60)`) produce an invalid schedule that is
rejected by `build()`, just like an invalid cron string.

You can also capture the id the scheduler assigns to a task with `add_task_get_id`, which
is handy for addressing an unnamed task through the handle afterwards:

```rust,no_run
# use tasklet::{TaskBuilder, TaskScheduler};
# #[tokio::main]
# async fn main() {
let mut scheduler = TaskScheduler::default(chrono::Local);
let id = scheduler
.add_task_get_id(TaskBuilder::new(chrono::Local).every_seconds(5).build())
.unwrap();
let handle = scheduler.handle();
tokio::spawn(async move { handle.trigger(id); });
# }
```

## Naming, runtime control and history

Give a task a stable name and address it at runtime through the handle (added in 0.4.0).
Expand Down
59 changes: 59 additions & 0 deletions examples/schedule_helpers_and_streaming.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use log::info;
use simple_logger::SimpleLogger;
use std::time::Duration;
use tasklet::task::TaskStepStatusOk::Success;
use tasklet::{TaskBuilder, TaskScheduler};

/// Demonstrates the v0.4.1 additions:
///
/// * **Schedule helpers**: `every_seconds` builds the cron expression for you.
/// * **`add_task_get_id`**: capture the id of an unnamed task to address it later.
/// * **Live step streaming**: the handle observes step transitions *during* a run,
/// so a completed early step is visible while a later step is still in flight.
#[tokio::main]
async fn main() {
SimpleLogger::new().init().unwrap();

let mut scheduler = TaskScheduler::new(200, chrono::Local);

// A two-step task on a 2-second cadence built without writing raw cron. The
// second step is slow, so its predecessor shows as completed while it runs.
let task = TaskBuilder::new(chrono::Local)
.every_seconds(2)
.add_step("prepare", || async {
info!("step 1: prepare");
Ok(Success)
})
.add_step("work (slow)", || async {
info!("step 2: working...");
tokio::time::sleep(Duration::from_millis(1200)).await;
info!("step 2: done");
Ok(Success)
})
.build();

// Capture the assigned id so we can address the (unnamed) task through the handle.
let id = scheduler.add_task_get_id(task).unwrap();
info!("task registered with id {}", id);

// Poll the per-step snapshot while the task runs to watch it advance live.
let handle = scheduler.handle();
let observer = tokio::spawn(async move {
for _ in 0..12 {
tokio::time::sleep(Duration::from_millis(500)).await;
let steps: Vec<String> = handle
.step_states(id)
.into_iter()
.map(|s| format!("{}={:?}", s.description.as_deref().unwrap_or("-"), s.status))
.collect();
if !steps.is_empty() {
info!("[live steps] {}", steps.join(", "));
}
}
});

scheduler
.run_until(tokio::time::sleep(Duration::from_secs(6)))
.await;
observer.await.unwrap();
}
123 changes: 123 additions & 0 deletions src/builders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,88 @@ where
self
}

/// Run every `n` seconds.
///
/// A convenience wrapper over [`every`](Self::every) that builds the equivalent
/// cron expression, so you do not have to write one by hand. `n` must be between 1
/// and 59; other values produce an invalid schedule that is rejected by
/// [`build`](Self::build).
///
/// # Examples
///
/// ```rust
/// # use tasklet::TaskBuilder;
/// let _task = TaskBuilder::new(chrono::Local).every_seconds(5).build().unwrap();
/// ```
pub fn every_seconds(self, n: u32) -> TaskBuilder<T> {
self.every(&format!("*/{} * * * * * *", n))
}

/// Run every `n` minutes (at second 0).
///
/// A convenience wrapper over [`every`](Self::every). `n` must be between 1 and 59;
/// other values produce an invalid schedule that is rejected by
/// [`build`](Self::build).
///
/// # Examples
///
/// ```rust
/// # use tasklet::TaskBuilder;
/// let _task = TaskBuilder::new(chrono::Local).every_minutes(15).build().unwrap();
/// ```
pub fn every_minutes(self, n: u32) -> TaskBuilder<T> {
self.every(&format!("0 */{} * * * * *", n))
}

/// Run every `n` hours (at minute 0, second 0).
///
/// A convenience wrapper over [`every`](Self::every). `n` must be between 1 and 23;
/// other values produce an invalid schedule that is rejected by
/// [`build`](Self::build).
///
/// # Examples
///
/// ```rust
/// # use tasklet::TaskBuilder;
/// let _task = TaskBuilder::new(chrono::Local).every_hours(6).build().unwrap();
/// ```
pub fn every_hours(self, n: u32) -> TaskBuilder<T> {
self.every(&format!("0 0 */{} * * * *", n))
}

/// Run once a day at the given `hour` and `minute` (24-hour clock, second 0).
///
/// A convenience wrapper over [`every`](Self::every). `hour` must be 0-23 and
/// `minute` 0-59; other values produce an invalid schedule that is rejected by
/// [`build`](Self::build). The time is interpreted in the builder's timezone.
///
/// # Examples
///
/// ```rust
/// # use tasklet::TaskBuilder;
/// // Every day at 09:30.
/// let _task = TaskBuilder::new(chrono::Local).daily_at(9, 30).build().unwrap();
/// ```
pub fn daily_at(self, hour: u32, minute: u32) -> TaskBuilder<T> {
self.every(&format!("0 {} {} * * * *", minute, hour))
}

/// Run once an hour at the given `minute` (second 0).
///
/// A convenience wrapper over [`every`](Self::every). `minute` must be 0-59; other
/// values produce an invalid schedule that is rejected by [`build`](Self::build).
///
/// # Examples
///
/// ```rust
/// # use tasklet::TaskBuilder;
/// // At minute 15 of every hour.
/// let _task = TaskBuilder::new(chrono::Local).hourly_at(15).build().unwrap();
/// ```
pub fn hourly_at(self, minute: u32) -> TaskBuilder<T> {
self.every(&format!("0 {} * * * * *", minute))
}

/// Set the max repeats for the generated `Task`.
///
/// # Arguments
Expand Down Expand Up @@ -600,4 +682,45 @@ mod test {
assert_eq!(task.history_limit, DEFAULT_HISTORY_LIMIT);
assert!(task.name.is_none());
}

/// The schedule-helper builders produce valid, buildable cron expressions. (E1)
#[test]
fn test_schedule_helpers_build_valid_expressions() {
let cases = [
(
TaskBuilder::new(chrono::Utc).every_seconds(5),
"*/5 * * * * * *",
),
(
TaskBuilder::new(chrono::Utc).every_minutes(15),
"0 */15 * * * * *",
),
(
TaskBuilder::new(chrono::Utc).every_hours(6),
"0 0 */6 * * * *",
),
(
TaskBuilder::new(chrono::Utc).daily_at(9, 30),
"0 30 9 * * * *",
),
(
TaskBuilder::new(chrono::Utc).hourly_at(15),
"0 15 * * * * *",
),
];
for (builder, expected) in cases {
assert_eq!(builder.expression, expected);
// The helper parsed the expression eagerly, and it builds.
assert!(builder.schedule.is_some());
assert!(builder.build().is_ok());
}
}

/// A schedule helper given an out-of-range value fails at build time. (E1)
#[test]
fn test_schedule_helper_invalid_value_rejected() {
// Second 60 is out of range, so the generated expression is invalid.
let result = TaskBuilder::new(chrono::Utc).every_seconds(60).build();
assert!(matches!(result, Err(TaskError::InvalidCronExpression(_))));
}
}
7 changes: 6 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,12 @@
//! * **Observability** — query the live task set at runtime through
//! [`SchedulerHandle::task_count`] / [`SchedulerHandle::statuses`], including per-task
//! run history ([`SchedulerHandle::history`]) and per-step state
//! ([`SchedulerHandle::step_states`]).
//! ([`SchedulerHandle::step_states`]), which streams step transitions live during a run.
//! * **Schedule helpers** — build common cadences without raw cron:
//! [`TaskBuilder::every_seconds`], [`every_minutes`](TaskBuilder::every_minutes),
//! [`every_hours`](TaskBuilder::every_hours), [`hourly_at`](TaskBuilder::hourly_at) and
//! [`daily_at`](TaskBuilder::daily_at). Capture a task's id with
//! [`TaskScheduler::add_task_get_id`].
//! * **Runtime control** — name a task with [`TaskBuilder::name`] and pause, resume,
//! trigger or remove it at runtime through a [`SchedulerHandle`], by id or by name.
//! * **Shared data** — pass values between tasks and steps with a cheaply-clonable,
Expand Down
Loading
Loading