UNPKG

cronz-scheduler

Version:

A lightweight cron and interval scheduler for Node.js written in TypeScript.

76 lines (75 loc) 2.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CronScheduler = void 0; const cronUtils_1 = require("./utils/cronUtils"); class CronScheduler { constructor() { this.jobs = []; } addJob(name, expressionOrInterval, callback, options) { const isCron = typeof expressionOrInterval === "string"; if (isCron && !(0, cronUtils_1.validateCron)(expressionOrInterval)) { throw new Error("Invalid cron expression"); } const job = { name, callback, expression: isCron ? expressionOrInterval : undefined, intervalSeconds: isCron ? undefined : expressionOrInterval, endAt: options?.endAt, runCount: 0, }; this.jobs.push(job); } start() { this.jobs.forEach((job) => { if (job.intervalSeconds) { job.timerId = setInterval(() => { const now = new Date(); if (job.endAt && now >= job.endAt) { this.stopJob(job.name); return; } job.callback(); job.runCount++; }, job.intervalSeconds * 1000); } }); setInterval(() => { const now = new Date(); const [min, hour, day, month, weekday] = [ now.getMinutes(), now.getHours(), now.getDate(), now.getMonth() + 1, now.getDay(), ]; this.jobs.forEach((job) => { if (!job.expression) return; if ((0, cronUtils_1.matchTime)(job.expression.split(" ")[0], min) && (0, cronUtils_1.matchTime)(job.expression.split(" ")[1], hour) && (0, cronUtils_1.matchTime)(job.expression.split(" ")[2], day) && (0, cronUtils_1.matchTime)(job.expression.split(" ")[3], month) && (0, cronUtils_1.matchTime)(job.expression.split(" ")[4], weekday)) { if (job.endAt && now >= job.endAt) { this.stopJob(job.name); return; } job.callback(); job.runCount++; } }); }, 60 * 1000); } stopJob(name) { const index = this.jobs.findIndex((job) => job.name === name); if (index === -1) return; const job = this.jobs[index]; if (job.timerId) clearInterval(job.timerId); this.jobs.splice(index, 1); } } exports.CronScheduler = CronScheduler;