CronJobManager

CronJobManager is a scheduled task manager provided by NocoBase, based on cron. You can register scheduled tasks in your plugins for periodically executing specific logic.

Basic Usage

import { Plugin } from '@nocobase/server';

export default class PluginCronDemo extends Plugin {
  async load() {
    this.app.cronJobManager.addJob({
      cronTime: '0 0 * * *',       // Execute daily at 00:00
      onTick: async () => {
        console.log('Daily task: clean temporary data');
        await this.cleanTemporaryData();
      },
      timeZone: 'Asia/Shanghai',
      start: true,                  // Auto start
    });
  }

  async cleanTemporaryData() {
    // Execute cleanup logic here
  }
}

Parameter Description

The CronJobParameters type definition is as follows (from cron):

export declare interface CronJobParameters {
  cronTime: string | Date | DateTime;
  onTick: CronCommand;
  onComplete?: CronCommand | null;
  start?: boolean;
  timeZone?: string;
  context?: any;
  runOnInit?: boolean;
  utcOffset?: string | number;
  unrefTimeout?: boolean;
}
ParameterTypeDescription
cronTimestring | Date | DateTimeScheduled task time expression. Supports standard cron expressions, for example 0 0 * * * means execute daily at 00:00.
onTickfunctionTask main function. Will be triggered at the specified time.
onCompletefunctionExecutes when the task is stopped by job.stop() or after the onTick function completes.
timeZonestringSpecify the execution time zone (e.g., Asia/Shanghai).
contextanyContext when executing onTick.
runOnInitbooleanWhether to execute once immediately on initialization.
utcOffsetstring | numberSpecify the time zone offset.
unrefTimeoutbooleanControls whether the event loop stays active.

Cron Expression Examples

ExpressionMeaning
* * * * *Execute every minute
0 * * * *Execute every hour
0 0 * * *Execute daily at 00:00
0 9 * * 1Execute every Monday at 09:00
*/10 * * * *Execute every 10 minutes
Tip

You can use crontab.guru to help generate cron expressions.

Control Task Start and Stop

addJob() returns a job object that you can use to manually control the task:

const job = app.cronJobManager.addJob({ ... });
job.start();  // Start task
job.stop();   // Stop task
Tip

Scheduled tasks start and stop along with the application. You generally don't need to manually call start() or stop().