@dazejs/framework
Version:
Daze.js - A powerful web framework for Node.js
55 lines • 2.04 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScheduleService = void 0;
const events_1 = require("events");
const task_1 = require("./task");
class ScheduleService extends events_1.EventEmitter {
constructor(app) {
super();
this.tasks = [];
this.app = app;
}
register(scheduleKlass) {
if (scheduleKlass.prototype && Reflect.getMetadata('type', scheduleKlass) === 'schedule') {
this.parseScheduler(scheduleKlass);
}
}
parseScheduler(scheduleKlass) {
var _a;
const schedule = this.app.get(scheduleKlass);
const cornMap = (_a = Reflect.getMetadata('corn', scheduleKlass)) !== null && _a !== void 0 ? _a : new Map();
for (const [key, scheduler] of cornMap) {
this.tasks.push(new task_1.Task(scheduler, key, schedule[key].bind(schedule)));
}
}
start() {
let lastCheck = process.hrtime();
let lastExecution = Date.now();
const matchTime = () => {
if (!this.tasks.length)
return;
const elapsedTime = process.hrtime(lastCheck);
const elapsedMs = (elapsedTime[0] * 1e9 + elapsedTime[1]) / 1e6;
const missedExecutions = Math.floor(elapsedMs / 1000);
for (let i = missedExecutions; i >= 0; i--) {
const date = Date.now() - i * 1000;
if (lastExecution < date && i === 0) {
for (const task of this.tasks) {
if (task.match(new Date(date))) {
task.execute();
lastExecution = date;
}
}
}
}
lastCheck = process.hrtime();
this.timeout = setTimeout(matchTime, 1000);
};
matchTime();
}
stop() {
this.timeout && clearTimeout(this.timeout);
}
}
exports.ScheduleService = ScheduleService;
//# sourceMappingURL=schedule-service.js.map