Jobs

Run slow or scheduled work in the background, with retries.

A job is work that runs outside a request, such as sending a digest, rebuilding a cache or calling another service. You write a task, queue jobs for it from a hook or your server code, and a clock runs the jobs when they are due. This page explains how jobs work and how to define a task.

The queue is a table in your database. It needs no extra service and works on every database Tenon supports.

tenon.config.ts
import { defineCms, defineTask } from "tenoncms";

export default defineCms({
  // ...
  jobs: {
    tasks: {
      "send-digest": defineTask({
        meta: { description: "Emails the weekly digest" },
        run: async ({ payload, cms }) => {
          const posts = await cms.find("posts", { limit: 5 });
          // ... send the email
          return { sent: posts.length };
        },
      }),
    },
  },
});

Scheduled publishing and webhooks are jobs too. Everything in this section applies to them.

Use jobs

ToSee
Queue a job from a hook or your server codeQueue jobs
Run a task every night or every hourRecurring jobs
Make due jobs run on your hostThe clock
Watch, retry and cancel jobs in the adminManage jobs

Define a task

A task is a run function under a name in jobs.tasks. run gets:

  • payload: the JSON the job was queued with.
  • cms: the server API. It has no user, skips the access rules and reads published content. cms.withDrafts() reads drafts.
  • job: the id of the job and its attempts, counting this run.

What run returns is stored as the job's result. It SHOULD be JSON. A value that is not JSON, like a BigInt, logs a warning and the job still counts as done.

Task names MUST NOT start with tenon:. Tenon uses that prefix for its own tasks. A plugin prefixes its tasks with its name.

Failures and retries

A task that throws fails the attempt. The job runs again after 1 minute, then 2, then 4, and so on, until it reaches maxAttempts. Then its status is failed, and it stays until someone retries or cancels it.

A job can run more than once. A running job holds a lease of five minutes. If its host dies, or the task takes longer, the next tick runs it again. Write each task so that running it twice does no harm, for example by checking first whether the work is done.
  • Done jobs are deleted after 30 days.
  • A failed attempt also runs the lifecycle afterError hook, so your error reporting sees it.