2018-12-20 07:31:11 -06:00
|
|
|
import { logger } from '../../helpers/logger'
|
2019-04-11 08:38:53 -05:00
|
|
|
import * as Bluebird from 'bluebird'
|
2018-12-20 07:31:11 -06:00
|
|
|
|
2018-01-11 02:35:50 -06:00
|
|
|
export abstract class AbstractScheduler {
|
|
|
|
|
2018-06-14 11:06:56 -05:00
|
|
|
protected abstract schedulerIntervalMs: number
|
|
|
|
|
2018-01-11 02:35:50 -06:00
|
|
|
private interval: NodeJS.Timer
|
2018-12-20 07:31:11 -06:00
|
|
|
private isRunning = false
|
2018-01-11 02:35:50 -06:00
|
|
|
|
|
|
|
enable () {
|
2018-06-14 11:06:56 -05:00
|
|
|
if (!this.schedulerIntervalMs) throw new Error('Interval is not correctly set.')
|
|
|
|
|
|
|
|
this.interval = setInterval(() => this.execute(), this.schedulerIntervalMs)
|
2018-01-11 02:35:50 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
disable () {
|
|
|
|
clearInterval(this.interval)
|
|
|
|
}
|
|
|
|
|
2018-12-20 07:31:11 -06:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-11 08:38:53 -05:00
|
|
|
protected abstract internalExecute (): Promise<any> | Bluebird<any>
|
2018-01-11 02:35:50 -06:00
|
|
|
}
|