12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- 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<any>
- protected constructor(name: string) {
- this.name = name
- this.logger = newLogger(name)
- }
- protected abstract run(): Promise<void> | 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)
- }
- }
|