schedule.js
1.78 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
78
79
80
81
82
'use strict';
/*
node-schedule
A cron-like and not-cron-like job scheduler for Node.
*/
const { Job, scheduledJobs } = require('./Job')
/* API
invoke()
runOnDate(date)
schedule(date || recurrenceRule || cronstring)
cancel(reschedule = false)
cancelNext(reschedule = true)
Property constraints
name: readonly
job: readwrite
*/
/* Convenience methods */
function scheduleJob() {
if (arguments.length < 2) {
throw new RangeError('Invalid number of arguments');
}
const name = (arguments.length >= 3 && typeof arguments[0] === 'string') ? arguments[0] : null;
const spec = name ? arguments[1] : arguments[0];
const method = name ? arguments[2] : arguments[1];
const callback = name ? arguments[3] : arguments[2];
if (typeof method !== 'function') {
throw new RangeError('The job method must be a function.');
}
const job = new Job(name, method, callback);
if (job.schedule(spec)) {
return job;
}
return null;
}
function rescheduleJob(job, spec) {
if (job instanceof Job) {
if (job.reschedule(spec)) {
return job;
}
} else if (typeof job === 'string') {
if (scheduledJobs.hasOwnProperty(job)) {
if (scheduledJobs[job].reschedule(spec)) {
return scheduledJobs[job];
}
} else {
throw new Error('Cannot reschedule one-off job by name, pass job reference instead')
}
}
return null;
}
function cancelJob(job) {
let success = false;
if (job instanceof Job) {
success = job.cancel();
} else if (typeof job == 'string' || job instanceof String) {
if (job in scheduledJobs && scheduledJobs.hasOwnProperty(job)) {
success = scheduledJobs[job].cancel();
}
}
return success;
}
/* Public API */
module.exports = {
scheduleJob,
rescheduleJob,
scheduledJobs,
cancelJob
}