The ecosystem · jobs and cron
Work that runs later, and again until it is done
Work that shouldn't hold up a request (a welcome mail, a nightly cleanup, a call to a slow service) becomes a job: a row in your app's database (Postgres or SQLite), run in the background by workers, and tried again, a little later each time, until it succeeds. A schedule queues a job when its time comes. Send email from a job (packages/email), so an unreachable mail server is tried again.
packages/jobs is a plugin written in Roc, on what the server platform gives any plugin: the database and its notifications, background loops, and isolated calls (plugins).
Installing it#
Name the package in your app's header and list its plugin in App.program (this app also names packages/admin, for the jobs page):
app [program] { admin: "…/packages/admin/main.roc", jobs: "…/packages/jobs/main.roc", pf: platform "…/server/platform/main.roc" }import jobs.Cron
import jobs.Job
import Generated/App
import Jobs
…
program = App.program({
init!: |started| Ok({ started: started }),
…
# The jobs plugin (packages/jobs): the kinds of job the app's modules define, and a schedule. The
# jobs page (packages/admin) is a route of the app's, for members only (routes/(staff)/).
plugins: [
Job.plugin({ jobs: App.jobs, crons: [Cron.every("0 3 * * *", Jobs.welcome, { member: "everyone" })] }),
],
})Job.plugin takes one record; only jobs is required:
| Field | Default | What it is |
|---|---|---|
jobs | (required) | the kinds of job the workers run: App.jobs, every kind your modules define, found by rocx generate (and every build) |
crons | none | the schedules, each a Cron.every(…) (below) |
workers | 4 | how many jobs run at once |
retry_ms | 1000 | the wait before a failed job's second attempt, doubled for each attempt after |
on_failed! | nothing more | called with a job that failed for good, after it is logged: its kind, id, attempts and error (for an error tracker, packages/posthog's PostHog.job_failed!) |
keep_done_ms | a week | how long a done job is kept after it finished, then swept (below) |
keep_failed_ms | 30 days | the same for a failed or canceled job |
sweep_ms | an hour | how often finished jobs are swept, besides at start |
The plugin adds the queue's table, rocx_jobs (migration jobs/0001_jobs), the workers, the schedules' loop and the sweep. At start it checks every schedule and queues again the jobs a stop cut short. Without the plugin, queueing a job is an error that says to list it. An app on SQLite (the default, data/app.db) always has its database. On Postgres with no DATABASE_URL, the server doesn't start, and says why; under --dev and --debug it starts with a warning, the plugin runs nothing, and queueing returns the database's error.
A job#
A kind of job has a name and a function that does the work. The function gets your app's context (what its init! made) and the job's input, any type Roc can write as JSON. It answers Ok({}) when the work is done, or Err(why), and the job runs again later.
## Writes what it was told to the job log.
note_job : Job.Kind(_, { run : Str, said : Str })
note_job = Job.define(
"note",
|_context, { run, said }|
match Db.run!("insert into job_log (kind, said) values ('note', $1)", [Text("${run} ${said}")]) {
Ok(_) => Ok({})
Err(DbErr(why)) => Err(why)
},
)Define kinds at the top of a module's block, as here: rocx generate (and every build) finds every Job.define and Job.define_with there and lists them in App.jobs. A program written by hand lists Job.handler(kind) for each kind instead.
Queueing one#
("POST", "/jobs/note") =>
match Job.enqueue!(note_job, { run, said: Server.text_of(request) }, {}) {
Ok({}) => text(202, "queued")
Err(JobErr(why)) => text(500, why)
}
("POST", "/jobs/later") =>
match Job.enqueue!(note_job, { run, said: "later" }, { when: At(Time.now_millis!({}) + 400) }) {Job.enqueue!(kind, input, {}) queues a job to run when a worker is free. { when: At(ms) } holds it until that moment, in milliseconds since the epoch, as Time.now_millis! gives it (a past moment means now). when defaults to Now. The input is stored as JSON and read back as the kind's input type. Options have defaults: a call names only what it changes, and new options won't break it.
Queued inside Db.transaction!, a job is a row in the transaction: it runs only if the transaction commits (transactions). Job's errors are open unions ([JobErr(Str), ..others]), like Db's. So one transaction's body can use ? on its statements, its jobs and your own errors together, and its caller matches JobErr beside DbErr.
On a schedule#
Cron.every("0 3 * * *", nightly, {}) # five fields, UTC: at 03:00 each day
Cron.every("* * * * * *", tick_job, {}) # six begin with seconds: every secondA schedule in crons queues its job, with its input, each time it comes round. Cron syntax: five fields (minute hour day month weekday), or six with seconds first, always UTC. A field is *, a number, a range (1-5), a step (*/15) or a list of them (1,15,30). Months and weekdays may be named (JAN, MON).
Each scheduled job is keyed by its schedule and due second, so a restart never queues it twice, and a failed run is retried like any job. A schedule the parser (Roc too) can't read, or whose job the plugin doesn't run, stops the server at start, saying why.
Attempts, time limits and keys#
## A reminder: tried once, within a minute (`Job.define`'s are tried five times, with no limit).
reminder : Job.Kind(_, { member : Str })
reminder = Job.define_with("reminder", { attempts: 1, timeout_ms: 60_000 }, |_context, { member }| if (member.is_empty()) Err("no one to remind") else Ok({}))
## A member's reminder, a day from now: one at a time, keyed by the member, so a second is
## `Exists`, and nothing is queued.
remind_tomorrow! : Str => Try([Queued, Exists], [JobErr(Str)])
remind_tomorrow! = |member| Job.enqueue_keyed!(reminder, { member: member }, { when: At(Time.now_millis!({}) + 86_400_000), key: "reminder:${member}" })
## Not tomorrow after all: canceled, or moved to an hour from now. Each says how many it changed.
forget_reminder! : Str => Try(U64, [JobErr(Str)])
forget_reminder! = |member| Job.cancel!("reminder:${member}")
remind_sooner! : Str => Try(U64, [JobErr(Str)])
remind_sooner! = |member| Job.move!("reminder:${member}", At(Time.now_millis!({}) + 3_600_000))- Attempts and a time limit.
Job.define_with(name, { attempts, timeout_ms }, run!)makes a kind triedattemptstimes in all, each run withintimeout_msmilliseconds (0 means no limit). AJob.definekind gets five attempts and no limit. - Keys.
Job.enqueue_keyed!(kind, input, { key })(andwhen, as forenqueue!) answersQueued, orExistsand queues nothing when a job with that key is queued or running. The key is free again once that job is done, failed or canceled. A key names what the job is for (reminder:ada), so you can find the job by it:Job.cancel!(key)cancels the queued ones (not a running one), andJob.move!(key, when)moves the queued one to another time. Each says how many jobs it changed and, inside a transaction, takes effect only if it commits.
How jobs run#
- Each job is taken once. Workers are background loops. Each takes the next due job (
for update skip lockedon Postgres, so no two take the same one) and runs it in its own call, so a crash fails that job, not the worker. A waiting worker holds no thread. - Woken, not polling. When its transaction commits, a queued job notifies
rocx_jobs(Postgres'sNOTIFY, orDb.notify!on SQLite), which wakes the workers. Otherwise a worker sleeps until the next delayed job or retry is due. - Again, and later. A failed job (an
Err, a crash, or its time limit passing) runs again afterretry_ms, then twice that, and so on, until its kind's attempts are used up. Then it isfailed, with its last error, and stays inrocx_jobsuntil you retry it or it is swept. Each failure is logged as a warning; a job that failed for good is logged as an error, beforeon_failed!is called. - Within a time limit.
timeout_msis a deadline on each run. The first effect waiting past it (a database statement, a socket, a request to another server) ends the run like a crash, whatever the job does with errors: the statement is cancelled (on SQLite, interrupted), its connection closed, the run's memory freed, and the job fails withtimed out after …. Roc that never waits (a loop with no effect) is stopped too: the server interrupts its thread. - Across restarts. A job running when the server stopped runs again at the next start.
- Swept when old. Finished rows stay for the jobs page and for retries, then are deleted: done jobs
keep_done_msafter finishing (a week), failed or canceled oneskeep_failed_msafter (30 days). The sweep runs at start and everysweep_ms(an hour), a thousand rows a statement, on Postgres and SQLite. A schedule every ten seconds leaves 8,640 done jobs a day, so keep them for less (keep_done_ms: 60 * 60 * 1000). Queued and running jobs are never swept. - Another plugin's jobs. A package can bring its own kind of job, as packages/push does for sending. Its plugin lists
Job.call(kind)in its calls andJob.adopt!(kind)in its starts, and the workers run those jobs too.
Reading the queue#
## The last twenty reminders that failed, and why: what an app's own page of jobs might list.
failed_reminders! : {} => Try(List(Str), [JobErr(Str)])
failed_reminders! = |{}| {
rows = Job.list!({ state: "failed", kind: "reminder", before_id: 0, limit: 20 })?
Ok(
rows.map(
|row|
match row.last_error {
Some(why) => "${row.id.to_str()}: ${why}"
Null => row.id.to_str()
},
),
)
}Job.list!({ state, kind, before_id, limit }) reads jobs, newest first; "" and 0 mean any. Each is a Job.Row: id, kind, input (as JSON), state (queued, running, done, failed or canceled), attempts and max_attempts, key, last error, and times in milliseconds. Everything else the jobs page uses is there for your pages too:
Job.get!(id)reads one job;Job.counts!({})counts the jobs of each kind in each state.Job.retry!(id)queues a failed or canceled job again,Job.cancel_id!(id)cancels a queued one, andJob.run_now!(id)makes a queued one due now.Cron.schedules!({})lists the schedules and when each comes round next;Cron.run_now!(name)queues a schedule's job now.Job.kinds!({})lists the kinds the plugin runs,Job.keeps!({})says how long it keeps finished jobs, andJob.changesis the live topic where the workers say what they start and finish.
The jobs page#
admins_only : Middleware(Str, Str)
admins_only = Middleware.make(|request, context, next!| if (Server.header(request, "x-admin") == Ok("yes")) next!(request, context) else Server.refused(403, "admins only"))
# … in its routes
# The jobs page (packages/admin), on a route of the app's (D-116), behind a guard of its own, with
# a link back to the app.
(_, "/admin/jobs") => Middleware.run!(admins_only, request, context, |passed, _| JobsPage.respond!(passed, { mount: "/admin/jobs", back: { label: "Acme Tests", href: "/" } }))packages/admin draws a page of the queue on a route of yours, for your admins only. Call JobsPage.respond!(request, { mount }) from a respond!, which answers every method, in a folder whose middleware knows who is an admin. mount is the route's path. The page needs the jobs plugin. back is a link to your app's own pages, first in the sidebar (none by default). At the sidebar's foot, Back to the app goes to the page of yours you came from, or to /.
import admin.JobsPage
# routes/(admin)/+middleware.roc guards it, as every route in (admin)/: middleware = Middlewares.admin
respond! = |{ request, .. }| JobsPage.respond!(request, { mount: "/admin/jobs" })- What it shows. Counts of queued, running, failed, done and canceled jobs; what finished in each five minutes of the last hour (done, done after a retry, failed); the latest failures, with why; each kind with its attempts, time limit and jobs per state; the schedules, in words where it can (
0 3 * * *is daily at 03:00), with their next time; and the jobs, fifty a page, newest first, with state, attempts, times, key and last error. The sidebar filters by state or kind. - One job (
?id=…) opens in a drawer over the list: its input (the JSON, laid out), last error, attempts, time limit, key, and timeline from queued to finished. - What it does. Retry, cancel and run now (for a job or a schedule) are plain forms that post to the page and redirect back. An action that can't be done gets a page saying why (409), and a post from another site's page is refused (403).
- As jobs change, it refreshes over a stream of events (
?events), and its times count on (3 s ago); Escape closes the drawer. Links and forms are answered in place with View Transitions: the sidebar stays still, the page fades, the drawer slides, and the stream stays open (no motion if the reader asks for less). Without script it is the same page with a refresh button, and links load whole pages. It follows the light or dark scheme and fits a phone. It needs no components or hydration, so it works whatever your pages are made of.
Not yet#
- A job's log isn't on the jobs page: what a run logged is in the server's log, with its job's id. The options are in
packages/jobs/PROPOSALS.md. - Missed schedules aren't caught up: a time that came round while the server was stopped is skipped.