FAQ - Help and questions

How do I run a periodic background job next to an axum server?

#tokio#background-tasks#scheduling#axumpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Start a task with tokio::spawn before axum::serve. Inside it use tokio::time::interval and select! between the next tick and a watch channel that signals shutdown. Set the missed-tick behaviour so a slow run does not trigger a burst of catch-up runs, and await the JoinHandle when stopping.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

src/main.rsrust
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);
}
text
the job ran at least 3 times: true
and did not run again after stopping: true
  • The first tick of an interval completes immediately, so the job runs once at start-up and then every period.
  • MissedTickBehavior::Skip makes 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::sleep in 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 JoinHandle holds the error. Log what job.await returns.
  • 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet