aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/schedulers/abstract-scheduler.ts
blob: f3d51a22e09f9df869dee6990a18e4f65f4981cd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import Bluebird from 'bluebird'
import { logger } from '../../helpers/logger'

export abstract class AbstractScheduler {

  protected abstract schedulerIntervalMs: number

  private interval: NodeJS.Timer
  private isRunning = false

  enable () {
    if (!this.schedulerIntervalMs) throw new Error('Interval is not correctly set.')

    this.interval = setInterval(() => this.execute(), this.schedulerIntervalMs)
  }

  disable () {
    clearInterval(this.interval)
  }

  async execute () {
    if (this.isRunning === true) return
    this.isRunning = true

    try {
      await this.internalExecute()
    } catch (err) {
      logger.error('Cannot execute %s scheduler.', this.constructor.name, { err })
    } finally {
      this.isRunning = false
    }
  }

  protected abstract internalExecute (): Promise<any> | Bluebird<any>
}