Spaces:
Running
Running
File size: 946 Bytes
d605f27 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
interface Timer {
now (): number;
};
type TaskFunctor = () => void;
export default class SchedulePool {
timer: Timer;
tasks: {[key: number]: Promise<void>} = {};
handlers: {[key: number]: number | NodeJS.Timeout} = {};
constructor (timer = Date) {
this.timer = timer;
}
clear () {
Object.values(this.handlers).forEach(handle => clearTimeout(handle as NodeJS.Timeout));
this.tasks = {};
this.handlers = {};
}
getTask (timestamp: number): Promise<void> {
const delay = Math.max(timestamp - this.timer.now(), 0);
if (!this.tasks[timestamp]) {
this.tasks[timestamp] = new Promise(resolve => {
this.handlers[timestamp] = setTimeout(resolve, delay);
}).then(() => {
delete this.tasks[timestamp];
delete this.handlers[timestamp];
});
}
return this.tasks[timestamp];
}
appendTask (timestamp: number, task: TaskFunctor) {
this.tasks[timestamp] = this.getTask(timestamp).then(task);
}
};
|