|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ImageProcessingQueue { |
|
|
constructor() { |
|
|
this.queue = [] |
|
|
this.processing = false |
|
|
this.results = new Map() |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async addTask(index, processor) { |
|
|
return new Promise((resolve, reject) => { |
|
|
const task = { |
|
|
index, |
|
|
processor, |
|
|
resolve, |
|
|
reject, |
|
|
addTime: Date.now() |
|
|
} |
|
|
|
|
|
this.queue.push(task) |
|
|
console.log(`[图片队列] 任务${index}已添加到队列,队列长度: ${this.queue.length}`) |
|
|
|
|
|
|
|
|
if (!this.processing) { |
|
|
this.processQueue() |
|
|
} |
|
|
}) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async processQueue() { |
|
|
if (this.processing || this.queue.length === 0) { |
|
|
return |
|
|
} |
|
|
|
|
|
this.processing = true |
|
|
console.log(`[图片队列] 开始处理队列,共${this.queue.length}个任务`) |
|
|
|
|
|
while (this.queue.length > 0) { |
|
|
const task = this.queue.shift() |
|
|
const startTime = Date.now() |
|
|
|
|
|
console.log(`[图片队列] 开始处理任务${task.index},等待时间: ${startTime - task.addTime}ms`) |
|
|
|
|
|
try { |
|
|
const result = await task.processor() |
|
|
const endTime = Date.now() |
|
|
const processingTime = endTime - startTime |
|
|
|
|
|
console.log(`[图片队列] 任务${task.index}处理完成,耗时: ${processingTime}ms`) |
|
|
|
|
|
|
|
|
this.results.set(task.index, { |
|
|
result, |
|
|
processingTime, |
|
|
completedAt: endTime |
|
|
}) |
|
|
|
|
|
task.resolve(result) |
|
|
} catch (error) { |
|
|
console.error(`[图片队列] 任务${task.index}处理失败: ${error.message}`) |
|
|
task.reject(error) |
|
|
} |
|
|
} |
|
|
|
|
|
this.processing = false |
|
|
console.log(`[图片队列] 队列处理完成`) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
getOrderedResults() { |
|
|
const sortedKeys = Array.from(this.results.keys()).sort((a, b) => a - b) |
|
|
return sortedKeys.map(key => ({ |
|
|
index: key, |
|
|
...this.results.get(key) |
|
|
})) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
clear() { |
|
|
this.queue = [] |
|
|
this.results.clear() |
|
|
this.processing = false |
|
|
console.log(`[图片队列] 队列已清空`) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
getStatus() { |
|
|
return { |
|
|
queueLength: this.queue.length, |
|
|
processing: this.processing, |
|
|
resultsCount: this.results.size |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
module.exports = ImageProcessingQueue |
|
|
|