JAVASCRIPT
Async Queue Processor - معالجة غير متزامنة
معالج Queue متقدم يدعم Concurrency Control، Retry Logic، وPriority Queues. مناسب للـ Background Jobs.
class AsyncQueue {
constructor(options = {}) {
this.queue = [];
this.processing = false;
this.concurrency = options.concurrency || 3;
this.activeJobs = 0;
this.retries = options.retries || 3;
this.retryDelay = options.retryDelay || 1000;
}
async add(job, priority = 0) {
return new Promise((resolve, reject) => {
this.queue.push({
job,
priority,
resolve,
reject,
attempts: 0
});
// Sort by priority (higher first)
this.queue.sort((a, b) => b.priority - a.priority);
this.process();
});
}
async process() {
if (this.processing || this.activeJobs >= this.concurrency) {
return;
}
if (this.queue.length === 0) {
this.processing = false;
return;
}
this.processing = true;
while (this.queue.length > 0 && this.activeJobs < this.concurrency) {
const item = this.queue.shift();
this.activeJobs++;
this.executeJob(item).finally(() => {
this.activeJobs--;
this.process();
});
}
}
async executeJob(item) {
try {
const result = await this.runWithRetry(item.job, item.attempts);
item.resolve(result);
} catch (error) {
if (item.attempts < this.retries) {
item.attempts++;
await this.delay(this.retryDelay * item.attempts);
this.queue.unshift(item); // Add back to front
this.process();
} else {
item.reject(error);
}
}
}
async runWithRetry(job, attempts) {
try {
return await job();
} catch (error) {
if (attempts < this.retries) {
throw error; // Will be retried
}
throw error;
}
}
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
getStats() {
return {
queued: this.queue.length,
active: this.activeJobs,
total: this.queue.length + this.activeJobs
};
}
}
// Usage
const queue = new AsyncQueue({ concurrency: 3, retries: 3 });
queue.add(async () => {
// Heavy operation
return await fetch('/api/data').then(r => r.json());
}, 10); // High priority
💡 مثال الاستخدام
استخدم Async Queue لمعالجة Background Jobs، Image Processing، أو Email Sending بكفاءة.
استخدام حر
هذا الكود متاح للاستخدام الحر. إذا كان لديك أسئلة أو تحتاج مساعدة، لا تتردد في التواصل معي.