Jobs
Queue jobs
Queue a job from a hook or your server code, and merge repeated calls into one run.
Queue a job with cms.jobs.queue(). It takes the task name, an optional payload and options:
await cms.jobs.queue("send-digest", { list: "weekly" });
await cms.jobs.queue("send-digest", { list: "daily" }, { runAt: new Date(Date.now() + 3_600_000) });
await cms.jobs.queue("send-digest", null, { maxAttempts: 1 });
3.key: builds the payload of the waiting job from its own payload and the new one.Queuing a task that is not defined throws.
Queue from a hook
Inside a hook, queue with the cms the hook gets. The job then joins the write's transaction:
cms/collections/posts.ts
hooks: {
afterChange: [
async ({ cms, doc }) => {
await cms.jobs.queue("send-digest", { id: doc.id });
},
],
},
- If the write rolls back, the job is gone too.
- The job runs only after the write commits.
- Give the hook a block body. A hook that returns a value replaces
doc, andqueue()returns the id of the job.
This makes a job the safe way to call another service after a write. A slow call inside the hook would hold the transaction open.
One job per key
With key, a task has at most one waiting job under that key. While one waits, a new call returns its id and queues nothing. Once the job runs, the key is free again.
Together with a later runAt, a key turns many calls into one run:
// At most one rebuild per minute, however many writes happen.
afterChange: [
async ({ cms }) => {
await cms.jobs.queue("rebuild", null, { key: "site", runAt: Date.now() + 60_000 });
},
],
When the task needs the data of every call, merge collects it into the waiting job:
cms.jobs.queue("reindex", [doc.id], {
key: "search",
runAt: Date.now() + 30_000,
merge: (queued, next) => [...(queued as string[]), ...(next as string[])],
});
- A key saves work, but does not guarantee one job. On Postgres, two writes that queue the first job at the same moment MAY create two.
- A failed job that waits for its retry holds its key. New calls join the retry.