Files
payloadcms/test/queues/tasks/EverySecondMax2Task.ts
Alessio Gravili c08b2aea89 feat: scheduling jobs (#12863)
Adds a new `schedule` property to workflow and task configs that can be
used to have Payload automatically _queue_ jobs following a certain
_schedule_.

Docs:
https://payloadcms.com/docs/dynamic/jobs-queue/schedules?branch=feat/schedule-jobs

## API Example

```ts
export default buildConfig({
  // ...
  jobs: {
    // ...
    scheduler: 'manual', // Or `cron` if you're not using serverless. If `manual` is used, then user needs to set up running /api/payload-jobs/handleSchedules or payload.jobs.handleSchedules in regular intervals
    tasks: [
      {
        schedule: [
          {
            cron: '* * * * * *',
            queue: 'autorunSecond',
            // Hooks are optional
            hooks: {
              // Not an array, as providing and calling `defaultBeforeSchedule` would be more error-prone if this was an array
              beforeSchedule: async (args) => {
                // Handles verifying that there are no jobs already scheduled or processing.
                // You can override this behavior by not calling defaultBeforeSchedule, e.g. if you wanted
                // to allow a maximum of 3 scheduled jobs in the queue instead of 1, or add any additional conditions
                const result = await args.defaultBeforeSchedule(args)
                return {
                  ...result,
                  input: {
                    message: 'This task runs every second',
                  },
                }
              },
              afterSchedule: async (args) => {
                await args.defaultAfterSchedule(args) // Handles updating the payload-jobs-stats global
                args.req.payload.logger.info(
                  'EverySecond task scheduled: ' +
                  (args.status === 'success' ? args.job.id : 'skipped or failed to schedule'),
                )
              },
            },
          },
        ],
        slug: 'EverySecond',
        inputSchema: [
          {
            name: 'message',
            type: 'text',
            required: true,
          },
        ],
        handler: ({ input, req }) => {
          req.payload.logger.info(input.message)
          return {
            output: {},
          }
        },
      }
    ]
  }
})
```

---
- To see the specific tasks where the Asana app for GitHub is being
used, see below:
  - https://app.asana.com/0/0/1210495300843759
2025-07-18 06:48:27 -04:00

68 lines
1.8 KiB
TypeScript

import {
countRunnableOrActiveJobsForQueue,
type TaskConfig,
type TaskType,
type WorkflowTypes,
} from 'payload'
export const EverySecondMax2Task: TaskConfig<'EverySecondMax2'> = {
schedule: [
{
cron: '* * * * * *',
queue: 'default',
hooks: {
beforeSchedule: async ({ queueable, req }) => {
const runnableOrActiveJobsForQueue = await countRunnableOrActiveJobsForQueue({
queue: queueable.scheduleConfig.queue,
req,
taskSlug: queueable.taskConfig?.slug as TaskType,
workflowSlug: queueable.workflowConfig?.slug as WorkflowTypes,
onlyScheduled: false, // Set to false, used to test it
})
return {
input: {
message: 'This task runs every second - max 2 per second',
},
shouldSchedule: runnableOrActiveJobsForQueue <= 1,
waitUntil: queueable.waitUntil,
}
},
afterSchedule: async (args) => {
await args.defaultAfterSchedule(args) // Handles updating the payload-jobs-stats global
args.req.payload.logger.info(
'EverySecondMax2 task scheduled: ' +
(args.status === 'success'
? String(args.job.id)
: args.status === 'skipped'
? 'skipped'
: 'error'),
)
},
},
},
],
slug: 'EverySecondMax2',
inputSchema: [
{
name: 'message',
type: 'text',
required: true,
},
],
handler: async ({ input, req }) => {
req.payload.logger.info(input.message)
await req.payload.create({
collection: 'simple',
data: {
title: input.message,
},
req,
})
return {
output: {},
}
},
}