Alcanforero
Alcanforero

Reputation: 21

Nestjs Schedule build uninterrupted cron running

I am using nestjs schedule for my cron but I have a question. How can I stop cron without interrupting the cron that are currently running to do a build and change the code? Or any suggestion or strategy?

Upvotes: 2

Views: 2818

Answers (1)

andsilver
andsilver

Reputation: 5972

I faced the same problem before.

  • I saved all cron jobs to a dedicated table.
  • I made a service to run and stop a cron job.
  • Each time the server restarts, this service finds the jobs from the table and restored them.

For example:

@Injectable()
export class AppJobService implements OnApplicationBootstrap {
  constructor(
     private schedule: SchedulerRegistry
  ) {}

  async onApplicationBootstrap() { // <- Nestjs hook invoked when the app bootstrapped
    const jobs = await Job.find(); // the jobs are all saved in `Job` table.
    jobs.forEach(job => {
        const cron = new CronJob(job.time, () => {}) // You can define the handler for each job type
        this.schedule.addCronJob(job.name, cron);
        cron.start();
    });
  }
}

Hope this helps you.

Upvotes: 1

Related Questions