当前位置:首页 > JavaScript

js 实现一个任务队列

2026-04-05 02:11:50JavaScript

实现基础任务队列结构

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

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

  addTask(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 failed:', error);
      }
    }
    this.isRunning = false;
  }
}

支持并发控制

限制同时执行的任务数量,避免资源过载:

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

  addTask(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.tasks = [];
  }

  addTask(task, priority = 0) {
    this.tasks.push({ task, priority });
    this.tasks.sort((a, b) => b.priority - a.priority);
  }

  async run() {
    while (this.tasks.length > 0) {
      const { task } = this.tasks.shift();
      await task();
    }
  }
}

错误处理与重试机制

为任务添加自动重试逻辑,提高容错性:

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

  addTask(task) {
    this.tasks.push(async () => {
      let retries = 0;
      while (retries <= this.maxRetries) {
        try {
          await task();
          break;
        } catch (error) {
          retries++;
          if (retries > this.maxRetries) throw error;
        }
      }
    });
  }

  async run() {
    while (this.tasks.length > 0) {
      const task = this.tasks.shift();
      await task();
    }
  }
}

使用示例

基础队列调用方式:

const queue = new TaskQueue();
queue.addTask(() => console.log('Task 1'));
queue.addTask(() => new Promise(resolve => setTimeout(resolve, 1000)));

并发队列调用方式:

js 实现一个任务队列

const concurrentQueue = new ConcurrentQueue(2);
for (let i = 0; i < 5; i++) {
  concurrentQueue.addTask(() => new Promise(resolve => {
    setTimeout(() => resolve(console.log(`Task ${i}`)), 500);
  }));
}

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

相关文章

uniapp队列下载

uniapp队列下载

uniapp 实现队列下载的方法 在 uniapp 中实现队列下载通常需要管理多个下载任务,确保它们按顺序执行。可以通过以下方法实现: 使用 Promise 和递归实现队列下载 定义一个下载队列数…

react如何确定任务优先级

react如何确定任务优先级

React 任务优先级机制 React 使用 Fiber 架构来管理任务优先级,通过Lane 模型(React 18+)或Expiration Time(旧版)实现优先级调度。以下是核心机制: 优先…

php实现redis消息队列

php实现redis消息队列

安装 Redis 扩展 确保 PHP 已安装 Redis 扩展。可以通过以下命令安装: pecl install redis 在 php.ini 中添加 extension=redis.so 并重启…

php 实现消息队列

php 实现消息队列

PHP 实现消息队列的方法 使用 Redis 实现消息队列 Redis 的 List 结构可以用于实现简单的消息队列。通过 LPUSH 和 RPOP 命令可以实现先进先出的队列。 $redis =…

php    队列实现

php 队列实现

队列的基本概念 队列是一种先进先出(FIFO)的数据结构,元素从队尾入队,从队头出队。PHP中可以通过数组或SplQueue类实现队列功能。 使用数组实现队列 PHP数组提供了array_push和…

php 队列实现

php 队列实现

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