当前位置:首页 > JavaScript

js 实现一个任务队列

2026-01-31 10:07:24JavaScript

实现基础任务队列结构

使用数组存储任务,通过push方法添加任务,shift方法取出任务执行:

class TaskQueue {
  constructor() {
    this.tasks = [];
    this.isRunning = false;
  }

  add(task) {
    this.tasks.push(task);
    if (!this.isRunning) this.run();
  }

  async run() {
    this.isRunning = true;
    while (this.tasks.length > 0) {
      const task = this.tasks.shift();
      try {
        await task();
      } catch (error) {
        console.error('Task error:', error);
      }
    }
    this.isRunning = false;
  }
}

添加并发控制功能

扩展基础队列实现最大并发数限制:

js 实现一个任务队列

class ConcurrentQueue {
  constructor(concurrency = 1) {
    this.tasks = [];
    this.concurrency = concurrency;
    this.running = 0;
  }

  add(task) {
    this.tasks.push(task);
    this.next();
  }

  next() {
    while (this.running < this.concurrency && this.tasks.length) {
      const task = this.tasks.shift();
      this.running++;
      task().finally(() => {
        this.running--;
        this.next();
      });
    }
  }
}

实现优先级队列

通过优先级参数控制任务执行顺序:

class PriorityQueue {
  constructor() {
    this.highPriority = [];
    this.lowPriority = [];
    this.isRunning = false;
  }

  add(task, priority = 'low') {
    const queue = priority === 'high' ? this.highPriority : this.lowPriority;
    queue.push(task);
    if (!this.isRunning) this.run();
  }

  async run() {
    this.isRunning = true;
    while (this.highPriority.length || this.lowPriority.length) {
      const queue = this.highPriority.length ? this.highPriority : this.lowPriority;
      const task = queue.shift();
      try {
        await task();
      } catch (error) {
        console.error('Task error:', error);
      }
    }
    this.isRunning = false;
  }
}

带错误恢复的队列实现

增加错误重试机制和失败回调:

js 实现一个任务队列

class ResilientQueue {
  constructor(maxRetries = 3) {
    this.tasks = [];
    this.maxRetries = maxRetries;
  }

  add(task, onError = null) {
    this.tasks.push({ task, retries: 0, onError });
    if (this.tasks.length === 1) this.run();
  }

  async run() {
    while (this.tasks.length) {
      const current = this.tasks[0];
      try {
        await current.task();
        this.tasks.shift();
      } catch (error) {
        current.retries++;
        if (current.retries >= this.maxRetries) {
          if (current.onError) current.onError(error);
          this.tasks.shift();
        }
      }
    }
  }
}

使用示例

基础队列使用方式:

const queue = new TaskQueue();
queue.add(() => new Promise(resolve => {
  setTimeout(() => {
    console.log('Task 1 done');
    resolve();
  }, 1000);
}));
queue.add(() => console.log('Task 2'));

并发队列示例:

const concurrent = new ConcurrentQueue(2);
for (let i = 1; i <= 5; i++) {
  concurrent.add(() => new Promise(resolve => {
    setTimeout(() => {
      console.log(`Task ${i} completed`);
      resolve();
    }, 1000);
  }));
}

标签: 队列任务
分享给朋友:

相关文章

php实现定时任务

php实现定时任务

PHP 实现定时任务的几种方法 在 PHP 中实现定时任务可以通过多种方式完成,具体选择取决于项目需求和服务器环境。以下是常见的实现方法: 使用 Cron 任务 Cron 是 Linux 系统中常用…

vue实现多任务进程

vue实现多任务进程

Vue 实现多任务进程的方法 在 Vue 中实现多任务进程通常需要结合 Web Workers 或其他异步处理技术。以下是几种常见的方法: 使用 Web Workers Web Workers 允许…

php数组实现队列

php数组实现队列

使用数组实现队列的基本方法 在PHP中,数组可以模拟队列的先进先出(FIFO)特性。通过内置的数组函数,可以轻松实现队列的基本操作。 初始化队列 $queue = []; 入队操作(enqueue…

php如何实现队列

php如何实现队列

PHP 实现队列的方法 使用数组模拟队列 PHP 数组可以模拟队列的先进先出(FIFO)特性。array_push 用于入队,array_shift 用于出队。 $queue = []; array…

java如何使用队列

java如何使用队列

队列的基本概念 队列是一种先进先出(FIFO)的数据结构,常用于任务调度、缓冲处理等场景。Java中可通过java.util.Queue接口及其实现类(如LinkedList、ArrayDeque)来…

Vue消息队列实现

Vue消息队列实现

Vue 消息队列实现 在 Vue 中实现消息队列可以通过多种方式完成,以下是几种常见的方法: 使用 Vuex 状态管理 Vuex 提供了一个集中式存储管理应用的状态,可以用于实现消息队列的功能。通过…