当前位置:首页 > 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);
  }));
}

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

相关文章

vue实现计划任务

vue实现计划任务

Vue 实现计划任务的方法 使用 Vue 的定时器(setInterval) 在 Vue 组件中,可以通过 setInterval 实现简单的计划任务。在组件的 mounted 生命周期钩子中启动定时…

php 队列实现

php 队列实现

使用数据库实现队列 在PHP中可以通过数据库表模拟队列行为,创建包含id、data、status和created_at字段的表。插入数据时状态设为pending,消费时更新为processing,完成…

js 实现异步队列

js 实现异步队列

异步队列的实现方法 在 JavaScript 中,实现异步队列可以通过多种方式,以下是几种常见的方法: 使用 Promise 链式调用 通过 Promise 的链式调用可以确保异步任务按顺序执行。每…

js 实现一个并发队列

js 实现一个并发队列

实现并发队列的基本思路 在JavaScript中实现并发队列,通常需要控制同时执行的异步任务数量。可以通过队列管理待执行任务,并结合Promise和计数器实现并发控制。 基于Promise的…

js队列实现

js队列实现

队列的基本概念 队列是一种先进先出(FIFO)的数据结构,支持在队尾添加元素(入队),在队头移除元素(出队)。JavaScript中可通过数组或链表实现队列。 基于数组的实现 利用数组的push和s…

java如何使用队列

java如何使用队列

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