Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现一个带并发限制的异步调度器 Scheduler,保证同时运行的任务最多有两个。完善下面代码中的 Scheduler 类,使得以下程序能正确输出。 #3

Open
wanghao1993 opened this issue May 17, 2023 · 0 comments

Comments

@wanghao1993
Copy link
Owner

class Scheduler {
  constructor() {
    this.queue = []; // 存储任务的队列
    this.maxConcurrent = 2; // 最大并发数
    this.runningCount = 0; // 当前正在运行的任务数
  }

  add(promiseCreator) {
    return new Promise((resolve, reject) => {
      // 将任务添加到队列中
      this.queue.push({ promiseCreator, resolve, reject });
      // 如果当前正在运行的任务数小于最大并发数,则执行任务
      if (this.runningCount < this.maxConcurrent) {
        this.runTask();
      }
    });
  }

  runTask() {
    if (this.queue.length === 0) return; // 队列为空,直接返回

    const { promiseCreator, resolve, reject } = this.queue.shift();
    this.runningCount++; // 当前正在运行的任务数加一

    promiseCreator()
      .then(resolve)
      .catch(reject)
      .finally(() => {
        this.runningCount--; // 当前正在运行的任务数减一
        this.runTask(); // 继续执行下一个任务
      });
  }
}

const timeout = (time) => new Promise((resolve) => setTimeout(resolve, time));

const scheduler = new Scheduler();

const addTask = (time, order) => {
  scheduler.add(() => timeout(time)).then(() => console.log(order));
};

addTask(1000, "1");
addTask(500, "2");
addTask(300, "3");
addTask(400, "4");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant