From adaa7ca413d793d29f87a605bb5c449ab7e4deb3 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 6 Feb 2018 17:29:28 +0100 Subject: [PATCH] feat(cron): wait promise before next run (#47) --- @xen-orchestra/cron/README.md | 3 +++ @xen-orchestra/cron/src/index.js | 21 ++++++++++++++------- 2 files changed, 17 insertions(+), 7 deletions(-) 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 () {