Scheduler | 调度器
有并发限制的 Promise 调度器
例如有 4 个任务,完成时间分别为,1000ms、500ms、300ms、400ms
在调度器中的执行完成顺序应该为 2、3、1、4
class Scheduler {
constructor(limit){
// 最大执行事件数量
this.max = limit;
// 事件收集队列
this.queues = [];
// 当前执行事件数量
this.count = 0;
}
// 事务添加
addTask(time, callback){
// 添加事务,注意 new 操作要在执行阶段
this.queues.push(()=> new Promise(rs => {
setTimeout(_=> rs(callback), time);
}))
}
// 事务开始
taskStart(){
// 循环并发执行
for(let i = 0; i< this.max; i++){
this.excute();
}
}
// 事务执行
excute(){
if(this.count >= this.max || !this?.queues?.length)return;
// 增记录
this.count ++;
// 取出 先进先出
let _promiseTask = this.queues.shift();
// 执行
_promiseTask()
.then(callback=>{
// 回调
callback&&callback();
// 减记录
this.count --;
// 递归,剩余执行
this.excute();
})
}
}
// 实例化一个调度器
let scheduler = new Scheduler(2);
const addTask = ( time, text ) => {
scheduler.addTask(time, ()=>console.log(text));
}
addTask(1000, '1');
addTask(500, '2');
addTask(300, '3');
addTask(400, '4');
scheduler.taskStart();
// 2 3 1 4