Jobs
Some work does not belong in a request: an import every night, a sync
with another system, statistics, mail in bulk, a long export a user asked
for. The jobs plugin runs that work outside requests, either on a
schedule or when a request asks for it. It needs nothing but PostgreSQL:
the queue is a table, and the workers are your application’s own binary.
Coming from Django: this is what Celery (with Celery beat for the schedules) or django-q do. There is no broker to run: no Redis, no RabbitMQ. A job is queued in the same database transaction as the request’s write, so a job never runs for a write that was rolled back.
Setting it up
Turn on the Cargo feature jobs:
# Cargo.toml of the application
rind = { version = "…", features = ["jobs"] }
Then give the plugin to the application, with its jobs and their schedules. The railway marks its journeys arrived every minute, and sends its mail through the queue:
#![allow(unused)]
fn main() {
// sample/src/jobs.rs
pub fn jobs() -> rind::jobs::Jobs {
rind::jobs::Jobs::new()
// Queued mail (`Mailer::queue`): a reservation's confirmation.
.mail()
.every("* * * * *", MarkArrived)
.expect("a schedule")
.timezone("Europe/Paris")
.expect("a time zone")
}
// sample/src/lib.rs, in app()
.with(jobs::jobs())
}
The plugin needs no environment variable. Its tables, rind_job_run
and rind_job_state, come with its migrations.
Then start a worker, a second process beside the server:
cargo run -p sample -- jobs-work --concurrency 4
Writing a job
A job is a Rust value that implements Job. The value holds the job’s
arguments: it is stored as JSON in the queue, so it derives Serialize
and Deserialize. Its run method does the work.
#![allow(unused)]
fn main() {
// sample/src/jobs.rs
use rind::jobs::{Interrupt, Job, JobCtx, JobError};
use serde::{Deserialize, Serialize};
/// Journeys whose arrival time has passed are `arrived`: every minute.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarkArrived;
impl Job for MarkArrived {
const NAME: &'static str = "timetable.mark_arrived";
/// Two at once would only do the same work twice.
const EXCLUSIVE: bool = true;
const INTERRUPT: Interrupt = Interrupt::Safe;
async fn run(self, ctx: &JobCtx) -> Result<(), JobError> {
let changed = ctx
.db
.execute_sql(
"UPDATE timetable_journey SET status = 'arrived' \
WHERE status IN ('planned', 'running') AND arrives_at < now()",
&[],
)
.await?;
ctx.db.wrote("timetable_journey");
// How many runs found nothing to do: a state kept across runs.
let idle: u64 = ctx.state().await?.unwrap_or(0);
ctx.set_state(&if changed == 0 { idle + 1 } else { 0 })
.await?;
ctx.note(format!("{changed} journeys arrived"));
Ok(())
}
}
}
NAME is the job’s name in the queue, in the log and on the command
line. The other constants are optional; they say how the job runs:
EXCLUSIVE(falseby default): only one run of the job at a time, across every worker. Use it for a job that two runs at once would only repeat, or would get wrong.TIMEOUT(an hour by default): a run that takes longer is stopped and marked failed.RETRIES(0by default): how many times a failed run is tried again. The next attempts wait 1 minute, then 5, then 30.INTERRUPT(Safeby default): what a worker that stops does with a run in progress. See Stopping a worker.
A JobError is a message. Any error type converts into one, so ?
works on database errors and the like.
What a job is given
JobCtx is to a job what Ctx is to a request:
ctx.db, the database;ctx.service::<T>(), the application’s services, as a request has them (ctx.service::<Mailer>());ctx.note(..), a line for the run’s log, kept with the run;ctx.state::<T>()andctx.set_state(&value), a value kept from one run to the next (in the tablerind_job_state): the last id an import read, the time of the last sync;ctx.run, the run’s id, andctx.attempt, its attempt number, starting at 1.
Running a job on a schedule
.every(pattern, job) runs job on a cron schedule of five fields
(minute, hour, day of the month, month, day of the week). It also
registers the job:
#![allow(unused)]
fn main() {
Jobs::new()
.every("* * * * *", MarkArrived)? // every minute
.every("7 7,13,20 * * *", Sync { full: false })? // at 7:07, 13:07, 20:07
.timezone("Europe/Paris")?
}
The schedules follow the time zone given by .timezone(..) (UTC by
default), across daylight saving changes.
Each scheduled time gives exactly one run, even with several workers.
When no worker was running at a scheduled time (during a deployment,
say), the run is queued once, late, when a worker comes back. With
.catch_up(false), such a missed time is skipped instead.
Coming from Django: this replaces Celery beat’s
CELERY_BEAT_SCHEDULE. There is no separate beat process: the workers take turns to queue the scheduled runs.
Queuing a job from a request
A request can ask for work to be done later. Register the job with
.job::<J>(), then queue it:
#![allow(unused)]
fn main() {
// in app()
.with(rind::jobs::Jobs::new().job::<RenderLayout>())
// in a hook or an action
let jobs = ctx.service::<rind::jobs::Jobs>().unwrap();
let run = jobs.queue(&ctx.db, RenderLayout { id }).await?;
}
queue gives the run’s id. A job the plugin does not know (one never
given to .job::<J>() or .every(..)) is refused with an error.
The run is written through ctx.db, so it is part of the request’s
transaction. A write that is rolled back takes its job with it, and a
worker never sees a run before the request has committed.
jobs.state_of(db, run) says where a run is: queued, running,
done, failed or skipped. A front end can poll it to wait for the
work it asked for.
jobs.queue_at(db, job, when, priority) queues a run for a later time,
with a priority: a higher priority runs first.
To send mail after the write commits, use mailer.queue(ctx, message):
a worker sends it, and tries again three times if the transport fails
(Mail). It needs .mail() on the plugin.
Workers
A worker is your application started with the command jobs-work:
cargo run -p sample -- jobs-work --concurrency 4
It runs up to --concurrency runs at once (4 by default). Start as many
workers as you like, on as many machines: they share the queue safely.
--only a,b limits a worker to the jobs named, so that a heavy job can
have workers of its own.
How a worker takes a run
A worker takes the next run that is due, with the highest priority
first, then the oldest. It uses FOR UPDATE SKIP LOCKED, so two workers
never take the same run. It holds the run under a lease (an hour), and
writes how the run went when it ends.
A worker that dies (killed, out of memory) leaves its runs running.
When their lease ends, another worker takes them again.
Every 20 seconds, one worker at a time queues the scheduled runs that are
due. Each idle worker looks for work every second (.poll(..) changes
that).
Stopping a worker
On SIGTERM or Ctrl-C, a worker stops taking runs. What it does with the
runs in progress depends on each job’s INTERRUPT:
Interrupt::Safe: the run is stopped at once and queued again. A worker started later runs it from the start.Interrupt::AvoidandInterrupt::Never: the worker waits for the run to end, within its grace period (a minute;.grace(..)changes it). A run that is still going when the grace ends is queued again.
Set your orchestrator’s stop timeout (Kubernetes’
terminationGracePeriodSeconds) a little longer than the grace.
The log of the runs
The table rind_job_run is both the queue and the log: one row per run,
with its job, its arguments, its state (queued, running, done,
failed, skipped), its attempt, the worker that ran it, its times, its
error and its notes.
A run is skipped when it was scheduled while another run of the same
exclusive job was still going. A run queued by a request in the same
situation waits and is tried again later.
The plugin adds commands to read and drive it:
cargo run -p sample -- jobs-list # each job, its schedules, its usual times
cargo run -p sample -- jobs-runs --failed # the last failed runs
cargo run -p sample -- jobs-run timetable.mark_arrived null # run it now, here
jobs-run runs a job at once, in the process you started, and prints
how it went. It is for a person at a terminal, or for a Kubernetes
CronJob if you prefer those to a worker’s schedules. The run is recorded
in the log like the others.
/ready tells how many runs are due and the age of the oldest
(Health): a number that keeps growing means the workers are
not keeping up, or are not running.
Testing jobs
In a test, there is no worker. jobs.run_pending(&db, &services) runs
every run that is due, here, one after the other, and gives what each
came to. jobs.schedule(&db) queues what the schedules say is due.
#![allow(unused)]
fn main() {
// sample/tests/jobs.rs
let jobs = state.services.get::<Jobs>().unwrap().clone();
// … a request that queues a mail …
let ran = jobs.run_pending(&db, &state.services).await.unwrap();
assert_eq!(ran, [("rind.mail".to_owned(), Outcome::Done)]);
}
Reference
The constants of Job
| Constant | Default | Meaning |
|---|---|---|
NAME | (required) | its name in the queue and the log |
EXCLUSIVE | false | one run at a time across every worker (a PostgreSQL advisory lock, per schema) |
TIMEOUT | an hour | a run past it fails, and is not retried |
RETRIES | 0 | runs again after a failure, after 1, 5, then 30 minutes |
INTERRUPT | Safe | Safe: stopped and queued again when a worker stops; Avoid, Never: waited for, within the grace |
Jobs
| Method | What it does |
|---|---|
Jobs::new() | the plugin, without jobs |
.job::<J>() | a job the workers run, and that requests may queue |
.mail() | the job that sends the mail Mailer::queue queues |
.every(pattern, job) | job on a cron schedule of five fields; registers the job |
.timezone(name) | the schedules’ time zone, UTC by default |
.catch_up(false) | a scheduled time missed while no worker ran is skipped, not run late |
.poll(duration) | how often an idle worker looks for a run (1 s) |
.grace(duration) | how long a stopping worker waits for runs it should not interrupt (60 s) |
queue(db, job), queue_at(db, job, when, priority) | queues a run; gives its id |
state_of(db, run) | the state of a run |
run_pending(db, services) | runs what is due, here (for tests) |
schedule(db) | queues the scheduled runs that are due (for tests) |
work(db, services, concurrency, only), work_until(…, stop) | a worker, in your own process |
Commands
| Command | What it does |
|---|---|
jobs-work [--concurrency n] [--only a,b] | a worker, until SIGTERM or Ctrl-C |
jobs-run <name> [json] | runs one now, in this process, and prints how it went |
jobs-queue <name> [json] | queues one |
jobs-list | each job, its schedules, how many runs are done, their median and longest times, the last |
jobs-runs [--failed] [--name n] [--limit n] | the last runs (30 by default) |
jobs-prune [--days n] | deletes the finished runs older than that (90 days by default) |
The json of jobs-run and jobs-queue is the job’s arguments. When it
is left out, {} is used: a job that is a unit struct, such as
MarkArrived, needs null instead.