1

As I am very new with loopback 4 and Typescript, knowing that we have to use custom booter to implement schedule tasks like Cron.

I require a code snippet which does that, i.e A custom booter class that implements Booter phases of configure, discover and load to Run a Cron

Monil Doshi
  • 151
  • 8

2 Answers2

3

I am not sure this is the way to do it, but this is working for me.

https://loopback.io/doc/en/lb4/Booting-an-Application.html#bootcomponent

Start with creating a component inside the project folder. I created src\components\cron.component.ts

import { Component } from "@loopback/core";
import { CronJob, CronCommand } from "cron"

export class CronJobsComponent implements Component {
    private cj: CronJob;
    constructor(){
        this.start()
    }

    async start(){
        this.cj = new CronJob('* * * * * *', this.showMessage)
        this.cj.start();
    }

    showMessage:CronCommand = async () => {
        console.log("inside cron jobs")
    }

}

Next import our component in the application.ts file

import { CronJobsComponent } from './components'

and register our new component inside the constructor

this.component(CronJobsComponent);

The corn job starts on application boot.

I used https://www.npmjs.com/package/cron and https://www.npmjs.com/package/@types/cron

Hope this helps you.

itssajan
  • 820
  • 8
  • 24
  • For some reason i see "inside cron jobs" printing twice per job. My CronJob runs every 10 seconds CronJob('*/10 * * * * * ', this.ShowMessage). Does anybody have any idea? – amazonotter Jul 01 '20 at 22:48
0

You can always create a cron endpoint.

http://localhost:3000/cron

You could then add a curl command to your crontab.

curl http://localhost:3000/cron

This method is a great way to handle seperation of concerns. If your api is a microservice running on kubernetes, you could call the cron endpoint using the Cron resource.

Just make sure that the endpoint is secure if your application is public.

Clay Risser
  • 3,272
  • 1
  • 25
  • 28