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
},
});
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
(config: ScheduledTaskConfig<C>) => ScheduledTask
id
options
execute
(injector: Injector) =>
configure
(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.
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
string
The unique identifier for the scheduled task.
description
string
The description for the scheduled task.
params
C
Optional parameters that will be passed to the execute
function.
schedule
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
number | string
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
boolean
true
Whether the scheduled task should be prevented from running if it is already running.
execute
(injector: Injector, config: C) => Promise<any>
The function that will be executed when the scheduled task is run.