-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
58 lines (51 loc) · 1.63 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
55
56
57
58
const debug = require('debug')('stop-agenda');
const stopAgenda = (agenda, config = {}) => {
if (typeof agenda !== 'object')
throw new Error('`agenda` must be an instance of Agenda');
config = Object.assign(
{
cancelQuery: {
repeatInterval: {
$exists: true,
$ne: null
}
},
checkIntervalMs: process.env.STOP_AGENDA_CHECK_INTERVAL
? parseInt(process.env.STOP_AGENDA_CHECK_INTERVAL, 10)
: 500
},
config
);
if (typeof config.cancelQuery !== 'object')
throw new Error('`config.cancelQuery` must be a MongoDB query object');
if (typeof config.checkIntervalMs !== 'number')
throw new Error('`config.checkIntervalMs` must be a Number');
// stop accepting new jobs
agenda.maxConcurrency(0);
return Promise.all([
new Promise((resolve, reject) => {
agenda.cancel(config.cancelQuery, (err, numRemoved) => {
if (err) return reject(err);
debug(`cancelled ${numRemoved} jobs`);
resolve();
});
}),
new Promise((resolve, reject) => {
// check every X ms for jobs still running
const jobInterval = setInterval(() => {
if (agenda._runningJobs.length > 0) {
debug(`${agenda._runningJobs.length} jobs still running`);
} else {
clearInterval(jobInterval);
// cancel recurring jobs so they get redefined on next server start
debug('attempting to run agenda.stop');
agenda.stop(err => {
if (err) return reject(err);
resolve();
});
}
}, config.checkIntervalMs);
})
]);
};
module.exports = stopAgenda;