use chrono::{DateTime, Utc};
use larust_core::AppError;
use larust_orm::Backend;
use sqlx::AnyPool;
use std::future::Future;
use std::pin::Pin;
use std::str::FromStr;
use std::time::Duration;
type BoxedTask =
Box<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), AppError>> + Send>> + Send + Sync>;
struct Entry {
cron: cron::Schedule,
task: BoxedTask,
name: Option<String>,
on_one_server: bool,
}
#[must_use]
pub struct Schedule {
entries: Vec<Entry>,
}
impl Default for Schedule {
fn default() -> Self {
Self::new()
}
}
impl Schedule {
pub fn new() -> Self {
Self {
entries: Vec::new(),
}
}
pub fn cron<F, Fut>(mut self, expr: &str, task: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
let parsed = cron::Schedule::from_str(expr).unwrap_or_else(|error| {
panic!(
"invalid cron expression {expr:?}: {error} -- Schedule::cron uses the `cron` \
crate's 7-field dialect (sec min hour day-of-month month day-of-week year), \
not the classic 5-field Unix cron format"
)
});
self.entries.push(Entry {
cron: parsed,
task: Box::new(move || Box::pin(task())),
name: None,
on_one_server: false,
});
self
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.entries
.last_mut()
.expect("Schedule::name called before registering any task")
.name = Some(name.into());
self
}
pub fn on_one_server(mut self) -> Self {
let entry = self
.entries
.last_mut()
.expect("Schedule::on_one_server called before registering any task");
assert!(
entry.name.is_some(),
"Schedule::on_one_server requires .name(...) first -- a task closure has no \
identity of its own to derive a cross-process lock key from"
);
entry.on_one_server = true;
self
}
pub fn every_minute<F, Fut>(self, task: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
self.cron("0 * * * * * *", task)
}
pub fn hourly<F, Fut>(self, task: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
self.cron("0 0 * * * * *", task)
}
pub fn daily<F, Fut>(self, task: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
self.cron("0 0 0 * * * *", task)
}
pub fn daily_at<F, Fut>(self, time: &str, task: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
let (hour, minute) = parse_hh_mm(time);
self.cron(&format!("0 {minute} {hour} * * * *"), task)
}
pub fn weekly<F, Fut>(self, task: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
self.cron("0 0 0 * * Sun *", task)
}
pub fn monthly<F, Fut>(self, task: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
self.cron("0 0 0 1 * * *", task)
}
}
fn parse_hh_mm(time: &str) -> (u32, u32) {
let (hour_str, minute_str) = time.split_once(':').unwrap_or_else(|| {
panic!("invalid time {time:?} for Schedule::daily_at -- expected \"HH:MM\"")
});
let hour: u32 = hour_str.parse().unwrap_or_else(|_| {
panic!("invalid hour in {time:?} for Schedule::daily_at -- expected \"HH:MM\"")
});
let minute: u32 = minute_str.parse().unwrap_or_else(|_| {
panic!("invalid minute in {time:?} for Schedule::daily_at -- expected \"HH:MM\"")
});
assert!(
hour < 24,
"hour out of range in {time:?} for Schedule::daily_at -- expected 00-23"
);
assert!(
minute < 60,
"minute out of range in {time:?} for Schedule::daily_at -- expected 00-59"
);
(hour, minute)
}
const LOCK_RETENTION_SECS: i64 = 7 * 24 * 60 * 60;
async fn ensure_lock_table(pool: &AnyPool) -> Result<(), AppError> {
let create_table = match larust_orm::backend() {
Backend::Sqlite => {
"CREATE TABLE IF NOT EXISTS scheduler_locks (\
task_name TEXT NOT NULL, \
scheduled_for_unix INTEGER NOT NULL, \
PRIMARY KEY (task_name, scheduled_for_unix)\
)"
}
Backend::MySql => {
"CREATE TABLE IF NOT EXISTS scheduler_locks (\
task_name VARCHAR(255) NOT NULL, \
scheduled_for_unix BIGINT NOT NULL, \
PRIMARY KEY (task_name, scheduled_for_unix)\
)"
}
Backend::Postgres => {
"CREATE TABLE IF NOT EXISTS scheduler_locks (\
task_name TEXT NOT NULL, \
scheduled_for_unix BIGINT NOT NULL, \
PRIMARY KEY (task_name, scheduled_for_unix)\
)"
}
};
sqlx::query(create_table)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
async fn claim(task_name: &str, at: DateTime<Utc>) -> Result<bool, AppError> {
let pool = larust_orm::pool()?;
ensure_lock_table(pool).await?;
let backend = larust_orm::backend();
let scheduled_for = at.timestamp();
let prune_sql = format!(
"DELETE FROM scheduler_locks WHERE task_name = {} AND scheduled_for_unix < {}",
larust_orm::placeholder(backend, 1),
larust_orm::placeholder(backend, 2),
);
sqlx::query(&prune_sql)
.bind(task_name)
.bind(scheduled_for - LOCK_RETENTION_SECS)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
let claim_sql = format!(
"INSERT INTO scheduler_locks (task_name, scheduled_for_unix) VALUES ({}, {})",
larust_orm::placeholder(backend, 1),
larust_orm::placeholder(backend, 2),
);
match sqlx::query(&claim_sql)
.bind(task_name)
.bind(scheduled_for)
.execute(pool)
.await
{
Ok(_) => Ok(true),
Err(sqlx::Error::Database(database)) if database.is_unique_violation() => Ok(false),
Err(source) => Err(AppError::Internal(Box::new(source))),
}
}
async fn run_due(schedule: &Schedule, at: DateTime<Utc>) {
for entry in &schedule.entries {
if !entry.cron.includes(at) {
continue;
}
if entry.on_one_server {
let name = entry.name.as_deref().unwrap();
match claim(name, at).await {
Ok(true) => {}
Ok(false) => {
tracing::info!(
task = name,
"scheduled task already claimed by another process this occurrence, \
skipping"
);
continue;
}
Err(error) => {
tracing::error!(
task = name,
%error,
"failed to claim scheduled task lock, skipping this occurrence"
);
continue;
}
}
}
match (entry.task)().await {
Ok(()) => {
tracing::info!(cron = entry.cron.source(), name = ?entry.name, "scheduled task ran");
}
Err(error) => {
tracing::error!(
cron = entry.cron.source(),
name = ?entry.name,
%error,
"scheduled task failed"
);
}
}
}
}
const TICK_INTERVAL: Duration = Duration::from_secs(1);
pub async fn work(schedule: Schedule) -> Result<(), AppError> {
let mut interval = tokio::time::interval(TICK_INTERVAL);
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
tracing::info!("scheduler worker started");
loop {
interval.tick().await;
run_due(&schedule, Utc::now()).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
fn assert_send_sync<T: Send + Sync>() {}
#[test]
fn schedule_is_send_and_sync() {
assert_send_sync::<Schedule>();
}
#[test]
fn every_minute_produces_the_expected_cron_source() {
let schedule = Schedule::new().every_minute(|| async { Ok(()) });
assert_eq!(schedule.entries[0].cron.source(), "0 * * * * * *");
}
#[test]
fn hourly_produces_the_expected_cron_source() {
let schedule = Schedule::new().hourly(|| async { Ok(()) });
assert_eq!(schedule.entries[0].cron.source(), "0 0 * * * * *");
}
#[test]
fn daily_produces_the_expected_cron_source() {
let schedule = Schedule::new().daily(|| async { Ok(()) });
assert_eq!(schedule.entries[0].cron.source(), "0 0 0 * * * *");
}
#[test]
fn weekly_produces_the_expected_cron_source() {
let schedule = Schedule::new().weekly(|| async { Ok(()) });
assert_eq!(schedule.entries[0].cron.source(), "0 0 0 * * Sun *");
}
#[test]
fn monthly_produces_the_expected_cron_source() {
let schedule = Schedule::new().monthly(|| async { Ok(()) });
assert_eq!(schedule.entries[0].cron.source(), "0 0 0 1 * * *");
}
#[test]
fn daily_at_parses_hh_mm_into_the_expected_cron_source() {
let schedule = Schedule::new().daily_at("13:07", || async { Ok(()) });
assert_eq!(schedule.entries[0].cron.source(), "0 7 13 * * * *");
}
#[test]
#[should_panic(expected = "invalid time")]
fn daily_at_panics_on_a_malformed_time() {
let _ = Schedule::new().daily_at("not-a-time", || async { Ok(()) });
}
#[test]
#[should_panic(expected = "hour out of range")]
fn daily_at_panics_on_an_out_of_range_hour() {
let _ = Schedule::new().daily_at("24:00", || async { Ok(()) });
}
#[test]
#[should_panic(expected = "invalid cron expression")]
fn cron_panics_on_an_invalid_expression() {
let _ = Schedule::new().cron("not a cron expression", || async { Ok(()) });
}
#[tokio::test]
async fn run_due_fires_a_task_exactly_at_a_matching_instant_not_a_neighboring_one() {
let matching_calls = Arc::new(AtomicUsize::new(0));
let calls = Arc::clone(&matching_calls);
let schedule = Schedule::new().cron("0 30 9 * * * *", move || {
let calls = Arc::clone(&calls);
async move {
calls.fetch_add(1, Ordering::SeqCst);
Ok(())
}
});
let matching = Utc.with_ymd_and_hms(2026, 8, 15, 9, 30, 0).unwrap();
let not_matching = Utc.with_ymd_and_hms(2026, 8, 15, 9, 31, 0).unwrap();
run_due(&schedule, not_matching).await;
assert_eq!(matching_calls.load(Ordering::SeqCst), 0);
run_due(&schedule, matching).await;
assert_eq!(matching_calls.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn a_failing_task_does_not_block_a_same_tick_sibling() {
let good_calls = Arc::new(AtomicUsize::new(0));
let calls = Arc::clone(&good_calls);
let schedule = Schedule::new()
.cron("0 0 12 * * * *", || async {
Err(AppError::Internal(Box::new(std::io::Error::other(
"deliberate test failure",
))))
})
.cron("0 0 12 * * * *", move || {
let calls = Arc::clone(&calls);
async move {
calls.fetch_add(1, Ordering::SeqCst);
Ok(())
}
});
let at = Utc.with_ymd_and_hms(2026, 8, 15, 12, 0, 0).unwrap();
run_due(&schedule, at).await;
assert_eq!(
good_calls.load(Ordering::SeqCst),
1,
"the second task should still have run despite the first failing"
);
}
#[test]
#[should_panic(expected = "requires .name(...) first")]
fn on_one_server_panics_without_a_name_first() {
let _ = Schedule::new().daily(|| async { Ok(()) }).on_one_server();
}
#[test]
#[should_panic(expected = "called before registering any task")]
fn name_panics_before_any_task_is_registered() {
let _ = Schedule::new().name("too-early");
}
#[test]
fn name_and_on_one_server_apply_to_the_most_recently_registered_task() {
let schedule = Schedule::new()
.daily(|| async { Ok(()) })
.hourly(|| async { Ok(()) })
.name("hourly-task")
.on_one_server();
assert_eq!(schedule.entries[0].name, None);
assert!(!schedule.entries[0].on_one_server);
assert_eq!(schedule.entries[1].name.as_deref(), Some("hourly-task"));
assert!(schedule.entries[1].on_one_server);
}
#[tokio::test]
async fn on_one_server_claims_exactly_once_per_task_and_occurrence() {
let dir = tempfile::tempdir().unwrap().keep();
let database_url = format!("sqlite://{}/test.sqlite", dir.display());
larust_orm::connect(&database_url).await.unwrap();
let at = Utc.with_ymd_and_hms(2026, 8, 15, 9, 30, 0).unwrap();
let later = Utc.with_ymd_and_hms(2026, 8, 15, 10, 30, 0).unwrap();
assert!(claim("report-task", at).await.unwrap());
assert!(!claim("report-task", at).await.unwrap());
assert!(claim("other-task", at).await.unwrap());
assert!(claim("report-task", later).await.unwrap());
let already_claimed_calls = Arc::new(AtomicUsize::new(0));
let calls = Arc::clone(&already_claimed_calls);
let unclaimed_calls = Arc::new(AtomicUsize::new(0));
let calls2 = Arc::clone(&unclaimed_calls);
let schedule = Schedule::new()
.cron("0 0 11 * * * *", move || {
let calls = Arc::clone(&calls);
async move {
calls.fetch_add(1, Ordering::SeqCst);
Ok(())
}
})
.name("report-task")
.on_one_server()
.cron("0 0 11 * * * *", move || {
let calls = Arc::clone(&calls2);
async move {
calls.fetch_add(1, Ordering::SeqCst);
Ok(())
}
})
.name("fresh-task")
.on_one_server();
let eleven = Utc.with_ymd_and_hms(2026, 8, 15, 11, 0, 0).unwrap();
claim("report-task", eleven).await.unwrap(); run_due(&schedule, eleven).await;
assert_eq!(
already_claimed_calls.load(Ordering::SeqCst),
0,
"a task whose occurrence was already claimed elsewhere must not run"
);
assert_eq!(
unclaimed_calls.load(Ordering::SeqCst),
1,
"a task whose occurrence was not yet claimed must run exactly once"
);
}
}