CronJob.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import cron from 'node-cron'
  2. import { newLogger } from '../utils/logger'
  3. import { Logger } from 'tslog'
  4. export abstract class CronJob {
  5. static tasks: cron.ScheduledTask[] = []
  6. static {
  7. process.on('SIGINT', () => {
  8. for (const task of this.tasks) {
  9. task.stop()
  10. }
  11. process.exit()
  12. })
  13. }
  14. private running = false
  15. protected name: string
  16. protected logger: Logger<any>
  17. protected constructor(name: string) {
  18. this.name = name
  19. this.logger = newLogger(name)
  20. }
  21. protected abstract run(): Promise<void> | void
  22. start(cronTime: string) {
  23. const task = cron.schedule(
  24. cronTime,
  25. async () => {
  26. if (this.running) return
  27. try {
  28. this.logger.info(`${this.name} job started.`)
  29. this.running = true
  30. await this.run()
  31. } catch (e) {
  32. this.logger.error('error occurred running cron job.', e)
  33. } finally {
  34. this.running = false
  35. this.logger.info(`${this.name} job finished.`)
  36. }
  37. },
  38. { runOnInit: true },
  39. )
  40. CronJob.tasks.push(task)
  41. }
  42. }