OperationQueue.js
2.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-12-30 11:27:18
* @LastEditors: 前端 qianduan01@didihu.com.cn
* @LastEditTime: 2024-12-30 20:10:04
* @FilePath: \gl-tape\utils\OperationQueue.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
class OperationQueue {
constructor(options = {}) {
this.queue = []
this.processing = false
this.maxQueueSize = options.maxQueueSize || 1000
this.operationTimeout = options.operationTimeout || 5 * 60 * 1000 // 5分钟超时
}
async enqueue(operation, context = '') {
if (this.queue.length >= this.maxQueueSize) {
throw new Error('Queue capacity exceeded')
}
return new Promise((resolve, reject) => {
this.queue.push({
operation,
context,
resolve,
reject,
timestamp: Date.now()
})
uni.$logger.local.info(`【操作入列】 [${context}], 当前队列长度: ${this.queue.length}`)
this.processQueue().catch(error => {
uni.$logger.local.error(`【操作队列】 队列处理发生错误: ${error.message}`)
})
})
}
async processQueue() {
if (this.processing) return
this.processing = true
try {
while (this.queue.length > 0) {
const { operation, context, resolve, reject, timestamp } = this.queue[0] // 使用peek而不是shift
uni.$logger.local.info(`【操作队列】 开始处理操作 [${context}], 等待时间: ${Date.now() - timestamp}ms`)
try {
// 添加超时处理
const result = await Promise.race([operation(), new Promise(resolve => setTimeout(() => resolve('Operation timeout'), this.operationTimeout))])
resolve(result)
uni.$logger.local.info(`【操作完成】 [${context}],耗时: ${Date.now() - timestamp}ms`)
} catch (error) {
uni.$logger.local.error(`【操作失败】 [${context}]: ${error.message}`)
reject(error)
} finally {
this.queue.shift() // 确保任务一定会被移除
uni.$logger.local.info(`【操作出列】 [${context}], 当前队列长度: ${this.queue.length}`)
}
// 添加任务间隔,避免过度占用CPU
await new Promise(resolve => setTimeout(resolve, 0))
}
} finally {
this.processing = false
}
}
// 新增:清空队列方法
clear() {
const rejectedItems = this.queue.splice(0, this.queue.length)
rejectedItems.forEach(item => {
item.reject(new Error('Queue was cleared'))
})
uni.$logger.local.warn(`【操作队列】 队列已清空,丢弃了 ${rejectedItems.length} 个任务`)
}
// 新增:获取队列状态
getStatus() {
return {
queueLength: this.queue.length,
processing: this.processing,
oldestTaskAge: this.queue[0] ? Date.now() - this.queue[0].timestamp : 0
}
}
}
export default OperationQueue