Build a task queue system for processing background jobs asynchronously
Create a robust task queue system that processes background jobs asynchronously, handles job retries, prioritization, and provides job status tracking.
class TaskQueue {
constructor() {
this.queue = [];
this.processing = false;
}
async enqueue(job) {
this.queue.push({ ...job, status: 'pending', id: Date.now() });
this.process();
}
async process() {
if (this.processing || this.queue.length === 0) return;
this.processing = true;
const job = this.queue.shift();
job.status = 'processing';
try {
await this.executeJob(job);
job.status = 'completed';
} catch (error) {
job.status = 'failed';
job.retries = (job.retries || 0) + 1;
}
this.processing = false;
this.process();
}
}