In Typescript, I have a controller class that has a method that I want to run daily at 5am.
My first thought was to schedule something using node-cron or node-scheduler, but these seem to be strictly for node projects, not typescript.
What I need to happen is a) transpile my entire typescript project into node and then b) Run the method as scheduled.
There doesn't seem to be any explanation on how to do this though. The explanations I do see are all about running a node.js function on some schedule, such as this one: I need a Nodejs scheduler that allows for tasks at different intervals
The below code illustrates my best approximation at what I'm trying to do.
controller.ts
import SomeOtherClass from './factory';
class MyController {
public async methodToRun(){
console.log ("King Chronos")
}
}
cron-job.ts
import MyController from "../src/controller";
let controller = new MyController();
var cronJob = require('cron').CronJob;
var myJob = new cronJob('00 30 11 * * 1-5', function(){
controller.methodToRun();
console.log("cron ran")
});
myJob.start();
npm i cron
npm i -D @types/cron
Since there are types available it works pretty fine with TypeScript. In my TypeScript I do something like:
import { CronJob } from 'cron';
class Foo {
cronJob: CronJob;
constructor() {
this.cronJob = new CronJob('0 0 5 * * *', async () => {
try {
await this.bar();
} catch (e) {
console.error(e);
}
});
// Start job
if (!this.cronJob.running) {
this.cronJob.start();
}
}
async bar(): Promise<void> {
// Do some task
}
}
const foo = new Foo();
Of course there is no need to start the job inside the constructor of Foo
. It is just an example.