-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
54 lines (44 loc) · 1.22 KB
/
index.js
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
import FIFO from './queues/fifo'
import LIFO from './queues/lifo'
export default class JobManager {
static queueTypes = { LIFO, FIFO }
static defaultOptions = {
workers: [{
jobsPerInterval: 1,
interval: 100,
}],
queueType: JobManager.queueTypes.LIFO,
}
constructor (options = {}) {
this._options = { ...JobManager.defaultOptions, ...options }
this._workers = []
this._queue = new this._options.queueType() // eslint-disable-line new-cap
}
dispatch = (job, ...args) => new Promise((resolve, reject) => this._queue.add(() => {
try {
resolve(job(...args))
} catch (e) {
reject(e)
}
}))
start = () => {
if (this._workers.length !== 0) return
this._workers = this._options.workers.map(worker => setInterval(this._dispatcher(worker.jobsPerInterval), worker.interval))
}
purgeQueue = () => this._queue.purge()
stop = () => {
while (this._workers.length > 0) clearInterval(this._workers.pop())
}
_dispatcher = (jobsToFinish) => {
return () => {
for (let i = 0; i < jobsToFinish; i++) {
const nextJob = this._queue.getNext()
if (nextJob) {
nextJob()
} else {
break
}
}
}
}
}