Answer#
A background job is an ordinary async task that never returns until told to stop. interval provides the beat; select! lets the same loop listen for a stop signal.
use std::{sync::{atomic::{AtomicU32, Ordering}, Arc}, time::Duration};
use tokio::{select, sync::watch, time::{interval, MissedTickBehavior}};
async fn cleanup_loop(runs: Arc<AtomicU32>, mut stop: watch::Receiver<bool>) {
let mut tick = interval(Duration::from_millis(50)); // the first tick completes immediately
tick.set_missed_tick_behavior(MissedTickBehavior::Skip); // a slow run does not cause a burst of catch-up runs
loop {
select! {
_ = tick.tick() => {
runs.fetch_add(1, Ordering::SeqCst); // the real work goes here: delete expired sessions, etc.
}
_ = stop.changed() => break, // the shutdown signal ends the loop between two runs
}
}
}
#[tokio::main]
async fn main() {
let runs = Arc::new(AtomicU32::new(0));
let (stop_tx, stop_rx) = watch::channel(false);
let job = tokio::spawn(cleanup_loop(runs.clone(), stop_rx));
tokio::time::sleep(Duration::from_millis(230)).await;
stop_tx.send(true).unwrap();
job.await.unwrap(); // wait until the task has really finished
let n = runs.load(Ordering::SeqCst);
println!("the job ran at least 3 times: {}", n >= 3);
tokio::time::sleep(Duration::from_millis(120)).await;
println!("and did not run again after stopping: {}", runs.load(Ordering::SeqCst) == n);
}the job ran at least 3 times: true
and did not run again after stopping: true- The first tick of an
intervalcompletes immediately, so the job runs once at start-up and then every period. MissedTickBehavior::Skipmakes a run that took longer than the period simply wait for the next beat instead of running several times in a row to catch up.stop.changed()completes when the sender sends. The loop leaves between two runs, never in the middle of one.- Awaiting the
JoinHandle(job.await) confirms the task really ended before the program moves on. The output shows no run happened after stopping.
In a server, create the watch channel next to the shutdown signal and send on it when graceful shutdown starts (see the thread on graceful shutdown).
Common mistakes#
- Using
std::thread::sleepin the loop. It blocks a runtime thread (see the thread on blocking work). - Letting a panic in the job go unnoticed: the task ends and the
JoinHandleholds the error. Log whatjob.awaitreturns. - Keeping the schedule only in memory when it must survive restarts. A job that must run "daily at 03:00" needs the last run time stored somewhere, such as a database row.
Related questions#
How do I run a job once, a little later?#
Spawn a task that does tokio::time::sleep(duration).await and then the work.
Sources#
- tokio,
interval: https://docs.rs/tokio/1.54.1/tokio/time/fn.interval.html (read 2026-12-05) - tokio,
MissedTickBehavior: https://docs.rs/tokio/1.54.1/tokio/time/enum.MissedTickBehavior.html (read 2026-12-05) - tokio,
watchchannel: https://docs.rs/tokio/1.54.1/tokio/sync/watch/index.html (read 2026-12-05)