Skip to main content

ScheduledTask

ScheduledTask

Use this class to define a scheduled task that will be executed at a given cron schedule.

Example

import { ScheduledTask } from '@vendure/core';

const task = new ScheduledTask({
id: 'test-job',
schedule: cron => cron.every(2).minutes(),
execute: async (injector, params) => {
// some logic here
},
});
Signature
class ScheduledTask<C extends Record<string, any> = Record<string, any>> {
constructor(config: ScheduledTaskConfig<C>)
id: void
options: void
execute(injector: Injector) => ;
configure(additionalConfig: Partial<Pick<ScheduledTaskConfig<C>, 'schedule' | 'timeout' | 'params'>>) => ;
}

constructor

method
(config: ScheduledTaskConfig<C>) => ScheduledTask

id

property

options

property

execute

method
(injector: Injector) =>

configure

method
(additionalConfig: Partial<Pick<ScheduledTaskConfig<C>, 'schedule' | 'timeout' | 'params'>>) =>

This method allows you to further configure existing scheduled tasks. For example, you may wish to change the schedule or timeout of a task, without having to define a new task.

Example

import { ScheduledTask } from '@vendure/core';

const task = new ScheduledTask({
id: 'test-job',
schedule: cron => cron.every(2).minutes(),
execute: async (injector, params) => {
// some logic here
},
});

// later, you can configure the task
task.configure({ schedule: cron => cron.every(5).minutes() });

ScheduledTaskConfig

The configuration for a scheduled task.

Signature
interface ScheduledTaskConfig<C extends Record<string, any> = Record<string, any>> {
id: string;
description?: string;
params?: C;
schedule: string | ((cronTime: typeof CronTime) => string);
timeout?: number | string;
preventOverlap?: boolean;
execute(injector: Injector, config: C): Promise<any>;
}

id

property
string

The unique identifier for the scheduled task.

description

property
string

The description for the scheduled task.

params

property
C

Optional parameters that will be passed to the execute function.

schedule

property
string | ((cronTime: typeof CronTime) => string)

The cron schedule for the scheduled task. This can be a standard cron expression or a function that returns a cron-time-generator expression.

Example

// Standard cron expression
{ schedule: '0 0-23/5 * * *', } // every 5 hours
{ schedule: '0 22 * * *', } // every day at 10:00 PM

// Cron-time-generator expression
{ schedule: cronTime => cronTime.every(2).minutes(), }
{ schedule: cronTime => cronTime.every(5).hours(), }

timeout

property
number | string
default:
60_000ms

The timeout for the scheduled task. If the task takes longer than the timeout, the task will be considered to have failed with a timeout error.

preventOverlap

property
boolean
default:
true

Whether the scheduled task should be prevented from running if it is already running.

execute

method
(injector: Injector, config: C) => Promise<any>

The function that will be executed when the scheduled task is run.