diff --git a/@xen-orchestra/cron/README.md b/@xen-orchestra/cron/README.md index ef9913101..cdbb30ee0 100644 --- a/@xen-orchestra/cron/README.md +++ b/@xen-orchestra/cron/README.md @@ -29,6 +29,9 @@ job.start() job.stop() ``` +> If the scheduled job returns a promise, its resolution (or +> rejection) will be awaited before scheduling the next run. + ### Pattern syntax ``` diff --git a/@xen-orchestra/cron/src/index.js b/@xen-orchestra/cron/src/index.js index 2d5e2b46e..a81928830 100644 --- a/@xen-orchestra/cron/src/index.js +++ b/@xen-orchestra/cron/src/index.js @@ -7,22 +7,29 @@ const MAX_DELAY = 2 ** 31 - 1 class Job { constructor (schedule, fn) { - const wrapper = scheduledRun => { - if (scheduledRun) { - fn() + const wrapper = () => { + const result = fn() + let then + if (result != null && typeof (then = result.then) === 'function') { + then.call(result, scheduleNext, scheduleNext) + } else { + scheduleNext() } + } + const scheduleNext = () => { const delay = schedule._nextDelay() this._timeout = delay < MAX_DELAY - ? setTimeout(wrapper, delay, true) - : setTimeout(wrapper, MAX_DELAY) + ? setTimeout(wrapper, delay) + : setTimeout(scheduleNext, MAX_DELAY) } - this._fn = wrapper + + this._scheduleNext = scheduleNext this._timeout = undefined } start () { this.stop() - this._fn() + this._scheduleNext() } stop () {