forked from pinpoint-apm/pinpoint-node-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.js
66 lines (54 loc) · 1.27 KB
/
scheduler.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
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Pinpoint Node.js Agent
* Copyright 2020-present NAVER Corp.
* Apache License v2.0
*/
'use strict'
const log = require('./logger')
const DEFAULT_INTERVAL = 3000
class Scheduler {
constructor(interval) {
this.interval = interval || DEFAULT_INTERVAL
this.timeout = null
this.jobList = []
}
start(runJobInitially) {
if (this.isRunning()) {
log.error('The scheduler is already running')
return
}
if (runJobInitially) {
setTimeout(() => this.runJobs(), 0)
}
log.info('The scheduler is scheduled to run every ' + this.interval + 'ms')
this.timeout = setInterval(() => this.runJobs(), this.interval)
}
stop() {
if (this.isRunning()) {
log.info('The scheduler is stopped')
clearInterval(this.timeout)
this.timeout = null
}
}
runJobs() {
this.jobList.forEach(job => job && job.apply())
}
isRunning() {
return this.timeout
}
addJob(jobFn) {
if (this.jobList.includes(jobFn)) {
log.error('It it not able to add duplicate job')
return
}
this.jobList.push(jobFn)
return () => this.removeJob(jobFn)
}
removeJob(jobFn) {
const i = this.jobList.indexOf(jobFn)
if (i >= 0) {
this.jobList.splice(i, 1)
}
}
}
module.exports = Scheduler