cron-schedule
Version:
A zero-dependency cron parser and scheduler for Node.js, Deno and the browser.
40 lines • 1.93 kB
JavaScript
import { longTimeout, wrapFunction } from '../utils.js';
/**
* A cron scheduler that is based on timers.
* It will create one timer for every scheduled cron.
* When the node timeout limit of ~24 days would be exceeded,
* it uses multiple consecutive timeouts.
*/
// biome-ignore lint/complexity/noStaticOnlyClass: a static class makes sense here to encapsulate the functionality
export class TimerBasedCronScheduler {
/**
* Creates a timeout, which will fire the given task on the next cron date.
* Returns a handle which can be used to clear the timeout using clearTimeoutOrInterval.
*/
static setTimeout(cron, task, opts) {
const nextSchedule = cron.getNextDate();
const timeout = nextSchedule.getTime() - Date.now();
return longTimeout(wrapFunction(task, opts === null || opts === void 0 ? void 0 : opts.errorHandler), timeout);
}
/**
* Creates an interval, which will fire the given task on every future cron date.
* Returns a handle which can be used to clear the interval using clearTimeoutOrInterval.
*/
static setInterval(cron, task, opts) {
var _a;
const handle = (_a = opts === null || opts === void 0 ? void 0 : opts.handle) !== null && _a !== void 0 ? _a : { timeoutId: undefined };
const { timeoutId } = TimerBasedCronScheduler.setTimeout(cron, () => {
wrapFunction(task, opts === null || opts === void 0 ? void 0 : opts.errorHandler)();
TimerBasedCronScheduler.setInterval(cron, task, Object.assign(Object.assign({}, opts), { handle }));
});
handle.timeoutId = timeoutId;
return handle;
}
/** Clears a timeout or interval, making sure that the function will no longer execute. */
static clearTimeoutOrInterval(handle) {
if (handle.timeoutId) {
clearTimeout(handle.timeoutId);
}
}
}
//# sourceMappingURL=timer-based.js.map