UNPKG

tiink

Version:

Tiink is NodeJS Job Schedule!

60 lines (59 loc) 2.15 kB
import { getTime, getTimeRelativeTo } from './utils/utils'; export class Tiink { constructor() { this.jobs = new Map(); } addJob(jobProps) { var _a; const { name } = jobProps; // This will check if there is an existent Job the same name. // If there is one stops and overwrite it. const job = this.jobs.get(name); if (job && ((_a = job === null || job === void 0 ? void 0 : job.action) === null || _a === void 0 ? void 0 : _a.running)) { clearTimeout(job.action.timeout); } this.jobs.set(name, Object.assign(Object.assign({}, jobProps), { action: this.setJobAction(jobProps, true) })); } setJobAction(jobProps, initial = false) { const { name, time, method, repeat } = jobProps; return { running: true, timeout: setTimeout(() => { method === null || method === void 0 ? void 0 : method(); const job = this.jobs.get(name); if (this.jobs.has(name) && job) { if (initial || repeat) { job.action = this.setJobAction(jobProps); } else { this.stopJob(name); } } }, getTime(time)) }; } stopJob(name) { var _a; const job = this.jobs.get(name); if (job && ((_a = job === null || job === void 0 ? void 0 : job.action) === null || _a === void 0 ? void 0 : _a.running)) { job.action.running = false; clearTimeout(job.action.timeout); } } restartJob(name) { var _a; const job = this.jobs.get(name); if (job) { if ((_a = job === null || job === void 0 ? void 0 : job.action) === null || _a === void 0 ? void 0 : _a.running) { clearTimeout(job.action.timeout); } job.action = this.setJobAction(job); } } deleteJob(name) { this.jobs.delete(name); } getTimeTo(time, date) { return getTimeRelativeTo(time, date); } }