@@ -7,24 +7,41 @@ const EventEmitter = require('events').EventEmitter
7
7
*/
8
8
9
9
const QueueEvent = {
10
- Tick : 'Tick'
10
+ Tick : 'Tick' ,
11
+ Push : 'Push' ,
12
+ Finish : 'Finish'
11
13
}
12
14
13
15
class ProcessQueue extends EventEmitter {
14
- constructor ( maximumLength , triggerTimeInterval = 10 ) {
16
+ constructor ( {
17
+ maximumLength = 500 ,
18
+ triggerTimeInterval = 5000 ,
19
+ // execute on push
20
+ proactiveMode = true ,
21
+ // execute next work on finish
22
+ continuousMode = true
23
+ } ) {
15
24
super ( )
16
25
this . max = maximumLength
17
26
this . triggerTime = triggerTimeInterval
18
27
this . taskMap = new Map ( )
19
28
this . queue = [ ]
20
29
this . lock = false
21
30
22
- this . on ( QueueEvent . Tick , ( ) => {
23
- if ( this . lock ) return
24
- this . lock = true
25
- setImmediate ( ( ) => {
26
- this . process ( )
27
- } )
31
+ this . on ( QueueEvent . Tick , this . onEventProcessFunc . bind ( this ) )
32
+ if ( proactiveMode ) {
33
+ this . on ( QueueEvent . Push , this . onEventProcessFunc . bind ( this ) )
34
+ }
35
+ if ( continuousMode ) {
36
+ this . on ( QueueEvent . Finish , this . onEventProcessFunc . bind ( this ) )
37
+ }
38
+ }
39
+
40
+ onEventProcessFunc ( ) {
41
+ if ( this . lock ) return
42
+ this . lock = true
43
+ setImmediate ( ( ) => {
44
+ this . process ( )
28
45
} )
29
46
}
30
47
@@ -62,7 +79,7 @@ class ProcessQueue extends EventEmitter {
62
79
this . taskMap . set ( id , true )
63
80
this . queue . push ( task )
64
81
this . start ( )
65
- this . emit ( QueueEvent . Tick )
82
+ this . emit ( QueueEvent . Push )
66
83
return true
67
84
}
68
85
@@ -79,7 +96,7 @@ class ProcessQueue extends EventEmitter {
79
96
const finishTask = ( ) => {
80
97
this . lock = false
81
98
setImmediate ( ( ) => {
82
- this . emit ( QueueEvent . Tick )
99
+ this . emit ( QueueEvent . Finish )
83
100
} )
84
101
}
85
102
task . processingFunc ( ) . then ( finishTask ) . catch ( finishTask )
0 commit comments