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

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

相关文章

php队列的实现

php队列的实现

PHP队列的实现方式 PHP中实现队列功能可以通过多种方式,根据需求选择适合的方案: 使用数组实现基础队列 PHP数组本身支持队列操作,利用array_push和array_shift函数: $q…

vue实现定时任务

vue实现定时任务

实现定时任务的几种方法 在Vue中实现定时任务可以通过多种方式,以下是几种常见的实现方法: 使用setInterval 在Vue组件的mounted生命周期钩子中设置setInterval,在bef…

vue任务表单实现指南

vue任务表单实现指南

Vue 任务表单实现方法 表单基础结构 使用 Vue 的 v-model 实现数据双向绑定,创建任务表单的基础结构: <template> <form @submit.prev…

php使用redis实现队列

php使用redis实现队列

PHP 使用 Redis 实现队列 Redis 是一个高性能的键值存储系统,支持多种数据结构,如字符串、哈希、列表、集合等。利用 Redis 的列表(List)数据结构可以轻松实现队列功能。以下是实现…

php如何实现定时任务

php如何实现定时任务

PHP实现定时任务的方法 PHP本身是脚本语言,没有内置的定时任务功能,但可以通过以下几种方式实现: 使用crontab(Linux系统) 在Linux系统中,crontab是最常用的定时任务工具。…

php实现调度任务

php实现调度任务

PHP 实现调度任务的方法 PHP 可以通过多种方式实现调度任务,以下是几种常见的方法: 使用 Cron 定时任务 Cron 是 Linux 系统自带的定时任务工具,可以配置 PHP 脚本定时执行。…