node.jscronnestjscron-task

Composite Cron job in Node / NestJS


I would like to create a composite cron job, which has 2 different variations for the job it executes.

The main job should run every 30 minutes, and execute command A.

The secondary job should run once per day, INSTEAD of the main job scheduled for that 30 minutes slot, and execute command B.

So the execution schedule would look like:

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB

etc. Every 30 minutes.

Any nice and clean way to implement this using a cron statement? Should the main job check what's the current time in the day and execute command B based on that condition? I would rather have a nice existing tool that can help define composite jobs such as this.


Solution

  • const SECONDARY_JOB_TIME = '11:00'; // this value could be an .env variable
    
    @Cron('*/30 * * * *') // run every 30mins
    public cronJob() {
      // check if secondary job should be triggered at this moment in time
      if(SECONDARY_JOB_TIME === this.getTime()) {
        return cronJobB(); //make sure to return so the execution stops here
      }
      
      return cronJobA();
    }
    
    // get the current time in HH:mm format
    private getTime(): string {
      const date = new Date()
      return `${date.getHours()}:${date.getMinutes()}`
    }