UNPKG

@mann-conomy/job-scheduler

Version:

A simple background job scheduler for the Mann-Conomy project.

91 lines 3.42 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const cron_1 = require("cron"); const events_1 = __importDefault(require("events")); const enums_1 = require("../resources/enums"); const utils_1 = require("../lib/utils"); class JobScheduler extends events_1.default { constructor(timeZone) { super(); this.jobs = new Map(); const result = (0, utils_1.validateTimeZone)(timeZone); if (!result.valid && result.error) { throw new TypeError("Invalid format or value for the specified time zone."); } this.timeZone = timeZone; } schedule(id, expression, resolver, options = {}) { const cronTime = (0, utils_1.validateCronTime)(expression); const cronOptions = (0, utils_1.validateCronOptions)(this.timeZone, options); const job = cron_1.CronJob.from(Object.assign({ cronTime, onTick: () => __awaiter(this, void 0, void 0, function* () { this.emit(enums_1.JobEvent.Started, id); try { const result = yield resolver(); this.emit(enums_1.JobEvent.Completed, id, result); } catch (error) { this.emit(enums_1.JobEvent.Error, id, error); } }), onComplete: () => { this.emit(enums_1.JobEvent.Stopped, id); } }, cronOptions)); this.jobs.set(id, job); this.emit(enums_1.JobEvent.Created, id); if (cronOptions.start) { job.start(); } } getJobs() { return Array.from(this.jobs.values()); } getJobIds() { return Array.from(this.jobs.keys()); } getScheduledJobs() { return this.jobs; } get(id) { const job = this.jobs.get(id); if (job == null) { throw new RangeError(); } return job; } start(id) { const job = this.get(id); if (!job.isActive && !job.isCallbackRunning) { job.start(); } } stop(id) { return __awaiter(this, void 0, void 0, function* () { const job = this.get(id); if (job.isActive || job.isCallbackRunning) { yield job.stop(); } }); } delete(id) { return __awaiter(this, void 0, void 0, function* () { yield this.stop(id); return this.jobs.delete(id); }); } getTimeZone() { return this.timeZone; } } exports.default = JobScheduler; //# sourceMappingURL=scheduler.js.map