2
1

abstract-scheduler.ts 841 B

1234567891011121314151617181920212223242526272829303132333435
  1. import { logger } from '../../helpers/logger'
  2. import * as Bluebird from 'bluebird'
  3. export abstract class AbstractScheduler {
  4. protected abstract schedulerIntervalMs: number
  5. private interval: NodeJS.Timer
  6. private isRunning = false
  7. enable () {
  8. if (!this.schedulerIntervalMs) throw new Error('Interval is not correctly set.')
  9. this.interval = setInterval(() => this.execute(), this.schedulerIntervalMs)
  10. }
  11. disable () {
  12. clearInterval(this.interval)
  13. }
  14. async execute () {
  15. if (this.isRunning === true) return
  16. this.isRunning = true
  17. try {
  18. await this.internalExecute()
  19. } catch (err) {
  20. logger.error('Cannot execute %s scheduler.', this.constructor.name, { err })
  21. } finally {
  22. this.isRunning = false
  23. }
  24. }
  25. protected abstract internalExecute (): Promise<any> | Bluebird<any>
  26. }