import cron from 'node-cron' import { newLogger } from '../utils/logger' import { Logger } from 'tslog' export abstract class CronJob { static tasks: cron.ScheduledTask[] = [] static { process.on('SIGINT', () => { for (const task of this.tasks) { task.stop() } process.exit() }) } private running = false protected name: string protected logger: Logger protected constructor(name: string) { this.name = name this.logger = newLogger(name) } protected abstract run(): Promise | void start(cronTime: string) { const task = cron.schedule( cronTime, async () => { if (this.running) return try { this.logger.info(`${this.name} job started.`) this.running = true await this.run() } catch (e) { this.logger.error('error occurred running cron job.', e) } finally { this.running = false this.logger.info(`${this.name} job finished.`) } }, { runOnInit: true }, ) CronJob.tasks.push(task) } }