Jobs – Queuing a new job in payload

Jobs are stored in the Payload database in the payload-jobs collection, and you can decide to keep a running list of all jobs, or configure Payload to delete the job when it has been successfully executed.

Queuing a new job

In order to queue a job, you can use the payload.jobs.queue function.

Here’s how you’d queue a new Job, which will run a createPostAndUpdate workflow:

const createdJob = await payload.jobs.queue({
 // Pass the name of the workflow
 workflow: 'createPostAndUpdate',
 // The input type will be automatically typed
 // according to the input you've defined for this workflow
 input: {
  title: 'my title',
 },
})

In addition to being able to queue new Jobs based on Workflows, you can also queue a job for a single Task:

const createdJob = await payload.jobs.queue({
 task: 'createPost',
 input: {
  title: 'my title',
 },
})

Cancelling Jobs

Payload allows you to cancel jobs that are either queued or currently running. When cancelling a running job, the current task will finish executing, but no subsequent tasks will run. This happens because the job checks its cancellation status between tasks.

Cancel a Single Job

To cancel a specific job, use the payload.jobs.cancelByID method with the job’s ID:

await payload.jobs.cancelByID({
 id: createdJob.id,
})

Cancel Multiple Jobs

To cancel multiple jobs at once, use the payload.jobs.cancel method with a Where query:

await payload.jobs.cancel({
 where: {
  workflowSlug: {
   equals: 'createPost',
  },
 },
})

Leave a comment

Your email address will not be published. Required fields are marked *