UNPKG

@hyperflake/job-scheduler

Version:

A simple and effective job scheduling module for Node.js, designed to manage and execute tasks based on cron-like schedules. This module utilizes `node-schedule` for precise timing and flexibility, making it ideal for applications that require specific ti

64 lines 1.85 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.JobScheduler = void 0; class ScheduledJob { constructor(cb, timeout) { this.cb = cb; let intervalInMilliseconds; switch (timeout.unit) { case 'milliseconds': intervalInMilliseconds = timeout.interval; break; case 'seconds': intervalInMilliseconds = timeout.interval * 1000; break; case 'minutes': intervalInMilliseconds = timeout.interval * 1000 * 60; break; case 'hours': intervalInMilliseconds = timeout.interval * 1000 * 60 * 60; break; } this.intervalId = setInterval(this.cb, intervalInMilliseconds); } invoke() { this.cb(); } cancel() { clearInterval(this.intervalId); } } class JobScheduler { constructor() { this.jobMap = {}; } schedule(jobName, timeout, cb) { if (this.jobMap[jobName]) { console.warn(`A job named ${jobName} already exists.`); return; } this.jobMap[jobName] = new ScheduledJob(cb, timeout); } cancel(jobName) { if (!this.jobMap[jobName]) { console.warn(`No job named ${jobName} found.`); return; } this.jobMap[jobName].cancel(); } invoke(jobName) { if (!this.jobMap[jobName]) { console.warn(`No job named ${jobName} found.`); return; } this.jobMap[jobName].invoke(); } destroy() { Object.keys(this.jobMap).forEach((jobName) => { this.jobMap[jobName].cancel(); }); this.jobMap = {}; } } exports.JobScheduler = JobScheduler; //# sourceMappingURL=scheduler.js.map