Priority queue with concurrency — process jobs by priority with limits.
1class PriorityQueue {2 constructor(concurrency = 3) {3 this.queue = [];4 this.running = 0;5 this.concurrency = concurrency;6 }78 add(job, priority = 0) {9 return new Promise((resolve, reject) => {10 this.queue.push({ job, priority, resolve, reject });11 this.queue.sort((a, b) => b.priority - a.priority);12 this.process();13 });14 }1516 async process() {17 while (this.running < this.concurrency && this.queue.length > 0) {18 const item = this.queue.shift();19 this.running++;2021 try {22 const result = await item.job();23 item.resolve(result);24 } catch (err) {25 item.reject(err);26 } finally {27 this.running--;28 this.process();29 }30 }31 }32}3334// Usage35const queue = new PriorityQueue(3);3637queue.add(() => sendEmail(data), 10); // high priority38queue.add(() => processImage(data), 5); // medium39queue.add(() => generateReport(data), 1); // low
BullMQ alternative:
1const queue = new Queue("jobs");2await queue.add("task", data, { priority: 10 });