use chrono::{DateTime, Datelike, Timelike, Utc};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
pub trait TaskResult {
fn into_result(self) -> Result<(), BoxError>;
}
impl TaskResult for () {
fn into_result(self) -> Result<(), BoxError> {
Ok(())
}
}
impl<Er: Into<BoxError>> TaskResult for Result<(), Er> {
fn into_result(self) -> Result<(), BoxError> {
self.map_err(Into::into)
}
}
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
#[error("invalid schedule: {0}")]
pub struct CronError(pub String);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Cron {
minute: u64,
hour: u64,
dom: u64,
month: u64,
dow: u64,
dom_star: bool,
dow_star: bool,
}
fn field(src: &str, min: u32, max: u32) -> Result<(u64, bool), CronError> {
let err = |m: &str| CronError(format!("{m} in `{src}`"));
let mut mask = 0u64;
for part in src.split(',') {
let (range, step) = match part.split_once('/') {
Some((r, s)) => (r, s.parse::<u32>().map_err(|_| err("bad step"))?),
None => (part, 1),
};
if step == 0 {
return Err(err("zero step"));
}
let num = |s: &str| s.parse::<u32>().map_err(|_| err("bad number"));
let (lo, hi) = if range == "*" {
(min, max)
} else if let Some((a, b)) = range.split_once('-') {
(num(a)?, num(b)?)
} else {
let a = num(range)?;
(a, if part.contains('/') { max } else { a })
};
if lo < min || hi > max || lo > hi {
return Err(err("out of range"));
}
let mut v = lo;
while v <= hi {
mask |= 1 << v;
v += step;
}
}
Ok((mask, src.starts_with('*')))
}
impl Cron {
pub fn parse(expr: &str) -> Result<Self, CronError> {
let f: Vec<&str> = expr.split_whitespace().collect();
let [m, h, dom, mon, dow] = f[..] else {
return Err(CronError(format!("expected 5 fields in `{expr}`")));
};
let (minute, _) = field(m, 0, 59)?;
let (hour, _) = field(h, 0, 23)?;
let (dom, dom_star) = field(dom, 1, 31)?;
let (month, _) = field(mon, 1, 12)?;
let (mut dow, dow_star) = field(dow, 0, 7)?;
if dow & (1 << 7) != 0 {
dow = (dow & !(1 << 7)) | 1; }
Ok(Self {
minute,
hour,
dom,
month,
dow,
dom_star,
dow_star,
})
}
pub fn matches(&self, t: DateTime<Utc>) -> bool {
let bit = |mask: u64, v: u32| mask & (1 << v) != 0;
let dom = bit(self.dom, t.day());
let dow = bit(self.dow, t.weekday().num_days_from_sunday());
let day = if !self.dom_star && !self.dow_star {
dom || dow
} else {
dom && dow
};
bit(self.minute, t.minute())
&& bit(self.hour, t.hour())
&& bit(self.month, t.month())
&& day
}
}
type Task =
Arc<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), BoxError>> + Send>> + Send + Sync>;
pub struct Entry {
name: String,
cron: Cron,
task: Task,
no_overlap: bool,
running: Arc<AtomicBool>,
filters: Vec<Box<dyn Fn() -> bool + Send + Sync>>,
}
impl Entry {
pub fn cron(&mut self, expr: &str) -> Result<&mut Self, CronError> {
self.cron = Cron::parse(expr)?;
Ok(self)
}
fn set(&mut self, expr: &str) -> &mut Self {
self.cron = Cron::parse(expr).expect("built-in expression is valid");
self
}
pub fn every_minute(&mut self) -> &mut Self {
self.set("* * * * *")
}
pub fn every_five_minutes(&mut self) -> &mut Self {
self.set("*/5 * * * *")
}
pub fn every_n_minutes(&mut self, n: u32) -> &mut Self {
self.set(&format!("*/{} * * * *", n.clamp(1, 59)))
}
pub fn hourly(&mut self) -> &mut Self {
self.hourly_at(0)
}
pub fn hourly_at(&mut self, minute: u32) -> &mut Self {
self.set(&format!("{} * * * *", minute.min(59)))
}
pub fn daily(&mut self) -> &mut Self {
self.set("0 0 * * *")
}
pub fn daily_at(&mut self, hhmm: &str) -> Result<&mut Self, CronError> {
let bad = || CronError(format!("expected HH:MM, got `{hhmm}`"));
let (h, m) = hhmm.split_once(':').ok_or_else(bad)?;
let (h, m): (u32, u32) = (h.parse().map_err(|_| bad())?, m.parse().map_err(|_| bad())?);
self.cron(&format!("{m} {h} * * *"))
}
pub fn weekly(&mut self) -> &mut Self {
self.set("0 0 * * 0")
}
pub fn monthly(&mut self) -> &mut Self {
self.set("0 0 1 * *")
}
pub fn without_overlapping(&mut self) -> &mut Self {
self.no_overlap = true;
self
}
pub fn when(&mut self, f: impl Fn() -> bool + Send + Sync + 'static) -> &mut Self {
self.filters.push(Box::new(f));
self
}
}
struct Release(Arc<AtomicBool>);
impl Drop for Release {
fn drop(&mut self) {
self.0.store(false, Ordering::SeqCst);
}
}
#[derive(Default)]
pub struct Schedule {
entries: Vec<Entry>,
}
impl Schedule {
pub fn new() -> Self {
Self::default()
}
pub fn call<F, Fut>(&mut self, name: impl Into<String>, f: F) -> &mut Entry
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future + Send + 'static,
Fut::Output: TaskResult,
{
let task: Task = Arc::new(move || {
let fut = f();
Box::pin(async move { fut.await.into_result() })
});
self.entries.push(Entry {
name: name.into(),
cron: Cron::parse("* * * * *").expect("valid"),
task,
no_overlap: false,
running: Arc::new(AtomicBool::new(false)),
filters: Vec::new(),
});
self.entries.last_mut().expect("just pushed")
}
fn start_due(&self, now: DateTime<Utc>) -> Vec<tokio::task::JoinHandle<()>> {
let mut handles = Vec::new();
for e in &self.entries {
if !e.cron.matches(now) || !e.filters.iter().all(|f| f()) {
continue;
}
let guard = if e.no_overlap {
if e.running
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
.is_err()
{
tracing::warn!(task = %e.name, "scheduled task skipped, previous run still going");
continue;
}
Some(Release(e.running.clone()))
} else {
None
};
let (name, task) = (e.name.clone(), e.task.clone());
handles.push(tokio::spawn(async move {
let _guard = guard;
if let Err(err) = task().await {
tracing::error!(task = %name, %err, "scheduled task failed");
}
}));
}
handles
}
pub async fn run_due(&self, now: DateTime<Utc>) -> usize {
let handles = self.start_due(now);
let n = handles.len();
for h in handles {
if let Err(err) = h.await {
tracing::error!(%err, "scheduled task panicked");
}
}
n
}
pub async fn run(&self, shutdown: impl Future<Output = ()>) {
tokio::pin!(shutdown);
loop {
let now = Utc::now();
let next = now
.with_second(0)
.and_then(|t| t.with_nanosecond(0))
.unwrap_or(now)
+ chrono::Duration::minutes(1);
let wait = (next - now).to_std().unwrap_or_default();
tokio::select! {
_ = &mut shutdown => return,
_ = tokio::time::sleep(wait) => { self.start_due(next); }
}
}
}
pub fn spawn(
self,
shutdown: impl Future<Output = ()> + Send + 'static,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move { self.run(shutdown).await })
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
use std::sync::atomic::AtomicUsize;
fn t(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> DateTime<Utc> {
Utc.with_ymd_and_hms(y, mo, d, h, mi, 0).unwrap()
}
fn boom(msg: &str) -> Result<(), BoxError> {
panic!("{msg}")
}
#[test]
fn cron_table() {
let cases = [
("* * * * *", t(2026, 1, 5, 4, 7), true),
("*/15 * * * *", t(2026, 1, 5, 4, 30), true),
("*/15 * * * *", t(2026, 1, 5, 4, 31), false),
("0,30 9-17 * * *", t(2026, 1, 5, 17, 30), true),
("0,30 9-17 * * *", t(2026, 1, 5, 18, 0), false),
("0 0 * * 7", t(2026, 1, 4, 0, 0), true),
("0 0 * * 1-5", t(2026, 1, 4, 0, 0), false),
("5/20 * * * *", t(2026, 1, 5, 0, 45), true),
("0 0 1 * 1", t(2026, 1, 5, 0, 0), true), ("0 0 1 * 1", t(2026, 1, 6, 0, 0), false),
];
for (e, when, want) in cases {
assert_eq!(Cron::parse(e).unwrap().matches(when), want, "{e} at {when}");
}
}
#[test]
fn cron_invalid() {
for e in [
"",
"* * * *",
"* * * * * *",
"60 * * * *",
"* 24 * * *",
"* * 0 * *",
"* * * 13 *",
"*/0 * * * *",
"5-1 * * * *",
"a * * * *",
"*/x * * * *",
"1- * * * *",
] {
assert!(Cron::parse(e).is_err(), "{e}");
}
let mut s = Schedule::new();
assert!(s.call("x", || async {}).daily_at("25:00").is_err());
assert!(s.call("y", || async {}).daily_at("nope").is_err());
}
#[tokio::test]
async fn run_due_fixed_times_when_and_failures() {
let hits = Arc::new(AtomicUsize::new(0));
let mut s = Schedule::new();
let h = hits.clone();
s.call("hourly", move || {
let h = h.clone();
async move {
h.fetch_add(1, Ordering::SeqCst);
}
})
.hourly_at(15);
s.call("fails", || async { Err::<(), _>("x") });
s.call("panics", || async { boom("boom") });
s.call("off", || async { boom("must not run") })
.when(|| false);
assert_eq!(s.run_due(t(2026, 1, 1, 5, 15)).await, 3);
assert_eq!(s.run_due(t(2026, 1, 1, 5, 16)).await, 2);
assert_eq!(hits.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn overlap_guard() {
let runs = Arc::new(AtomicUsize::new(0));
let mut s = Schedule::new();
let r = runs.clone();
s.call("slow", move || {
let r = r.clone();
async move {
r.fetch_add(1, Ordering::SeqCst);
tokio::time::sleep(std::time::Duration::from_millis(80)).await;
}
})
.without_overlapping();
let now = t(2026, 1, 1, 0, 0);
let (a, b) = tokio::join!(s.run_due(now), s.run_due(now));
assert_eq!(a + b, 1);
assert_eq!(s.run_due(now).await, 1); assert_eq!(runs.load(Ordering::SeqCst), 2);
}
}