Loopback 4 Cron Jobs, dynamically creating multiple class instances

22 Views Asked by At

I have a project requirement where I need to create multiple instances of loopback cron jobs dynamically. Basically I have multiple projects in a DB and each one will have their time set. In the loopback 4 documentation I only see an example of one instance, has anyone come across this issue before?

For example you have this:

import {CronJob, cronJob, CronJobConfig} from '@loopback/cron';
import {config, Provider, createBindingFromClass} from '@loopback/core';

@cronJob()
class MyCronJob extends CronJob {
  constructor() {
    super({
      name: 'job-B',
      onTick: () => {
        // do the work
      },
      cronTime: startIn(50),
      start: false,
    });
  }
}

const jobBinding = createBindingFromClass(MyCronJob);
app.add(jobBinding);

But what if I need multiple jobs each one with their own cronTime and name (project-1-job, project-2-job) and so on?
I realize this might be some class knowledge that I missing at the moment but it's been a while since I approached classes concepts. Thanks!

What I tried was creating a class that makes multiple instances dynamically but I realized that is not possible since the declaration is separate.

LE: My implementation

@cronJob()
class CronJob extends CronJob {
  constructor(
  ) {
    super({
      name: `cron-job`,
      onTick: async () => {// Code
      },
      cronTime: 'cron-time',
      timeZone: 'cron-timezone',
      start: true,
    });
  }
}

/**
 * This class will be bound to the application as a `LifeCycleObserver` during
 * `boot`
 */
@lifeCycleObserver('cron')
export class CronJobObserver implements LifeCycleObserver {
  private cronJobs: CronJob[] = [];

  constructor(
  ) {}

  /**
   * This method will be invoked when the application starts
   */
  async start(): Promise<void> {
    try {
      console.log('Starting CronJobObserver');

      // Schedule initial cron jobs
      this.scheduleCronJobs();

      console.log('Started CronJobObserver');
    } catch (e) {
      console.error(e);
      console.log('Fail to start CronJobObserver');
    }
  }

  /**
   * This method will be invoked when the application stops
   */
  async stop(): Promise<void> {
    try {
      console.log('Stopping CronJobObserver');

      // Stop all cron jobs
      this.cronJobs.forEach(job => job.stop());
      this.cronJobs = [];

      console.log('Stopped CronJobObserver');
    } catch (e) {
      console.error(e);
      console.log('Fail to stop CronJobObserver');
    }
  }

  /**
   * Schedule cron jobs based on database information
   */
  private async scheduleCronJobs() {
      // @ts-ignore
      this.cronJobs.push(
        new CronJob(),
      );
  }

  /**
   * Refresh cron jobs based on database information
   */
  async refreshCronJobs() {
    // Stop existing cron jobs
    this.cronJobs.forEach(job => job.stop());
    this.cronJobs = [];

    // Schedule new cron jobs based on updated database information
    await this.scheduleCronJobs();
    console.log('[observer] Cron Jobs have been refreshed!');
  }
}
0

There are 0 best solutions below