0
# Job Management
1
2
Advanced job management capabilities for controlling job lifecycle, handling events, and managing job state in Node Schedule.
3
4
## Capabilities
5
6
### Job Class
7
8
The Job class represents a scheduled task and extends EventEmitter for lifecycle event handling.
9
10
```javascript { .api }
11
/**
12
* Create a new job instance
13
* @param {string} [name] - Optional job name
14
* @param {function} job - Function to execute when job fires
15
* @param {function} [callback] - Optional callback executed after job completion
16
*/
17
class Job extends EventEmitter {
18
constructor(name?, job, callback?);
19
20
/** Job name (readonly) */
21
readonly name: string;
22
/** Job function to execute */
23
job: function;
24
/** Optional callback function */
25
callback: function | false;
26
/** Number of currently running invocations */
27
running: number;
28
/** Array of pending invocation objects */
29
pendingInvocations: Invocation[];
30
/** Whether this is a one-time job */
31
isOneTimeJob: boolean;
32
}
33
```
34
35
**Usage Examples:**
36
37
```javascript
38
const { Job } = require('node-schedule');
39
40
// Create a job manually
41
const job = new Job('myJob', function(fireDate) {
42
console.log('Job executed at:', fireDate);
43
});
44
45
// Schedule the job
46
job.schedule('*/5 * * * *'); // Every 5 minutes
47
48
// Listen for events
49
job.on('run', () => console.log('Job started'));
50
job.on('success', (result) => console.log('Job completed:', result));
51
job.on('error', (err) => console.error('Job failed:', err));
52
```
53
54
### Job Scheduling Methods
55
56
Methods for scheduling and rescheduling jobs with various timing specifications.
57
58
```javascript { .api }
59
/**
60
* Schedule the job with a timing specification
61
* @param {string|Date|object} spec - Schedule specification
62
* @returns {boolean} True if scheduling succeeded
63
*/
64
Job.prototype.schedule = function(spec);
65
66
/**
67
* Reschedule the job with new timing
68
* @param {string|Date|object} spec - New schedule specification
69
* @returns {boolean} True if rescheduling succeeded
70
*/
71
Job.prototype.reschedule = function(spec);
72
73
/**
74
* Schedule job to run on a specific date (alias for schedule)
75
* @param {Date} date - Date to run the job
76
* @returns {boolean} True if scheduling succeeded
77
*/
78
Job.prototype.runOnDate = function(date);
79
```
80
81
### Job Control Methods
82
83
Methods for controlling job execution and lifecycle.
84
85
```javascript { .api }
86
/**
87
* Cancel all pending invocations of the job
88
* @param {boolean} [reschedule=false] - Whether to reschedule recurring jobs
89
* @returns {boolean} True if cancellation succeeded
90
*/
91
Job.prototype.cancel = function(reschedule);
92
93
/**
94
* Cancel only the next pending invocation
95
* @param {boolean} [reschedule=true] - Whether to reschedule the next occurrence
96
* @returns {boolean} True if cancellation succeeded
97
*/
98
Job.prototype.cancelNext = function(reschedule);
99
100
/**
101
* Manually invoke the job function
102
* @param {Date} [fireDate] - Date to pass to the job function
103
* @returns {*} Result of the job function
104
*/
105
Job.prototype.invoke = function(fireDate);
106
```
107
108
### Job Information Methods
109
110
Methods for inspecting job state and scheduling information.
111
112
```javascript { .api }
113
/**
114
* Get the date of the next scheduled invocation
115
* @returns {Date|null} Next invocation date or null if no pending invocations
116
*/
117
Job.prototype.nextInvocation = function();
118
119
/**
120
* Get the total number of times this job has been triggered
121
* @returns {number} Count of triggered jobs
122
*/
123
Job.prototype.triggeredJobs = function();
124
125
/**
126
* Set the total number of times this job has been triggered
127
* @param {number} count - New triggered jobs count
128
*/
129
Job.prototype.setTriggeredJobs = function(count);
130
131
/**
132
* Track a new invocation (internal use)
133
* @param {Invocation} invocation - Invocation to track
134
*/
135
Job.prototype.trackInvocation = function(invocation);
136
137
/**
138
* Stop tracking an invocation (internal use)
139
* @param {Invocation} invocation - Invocation to stop tracking
140
*/
141
Job.prototype.stopTrackingInvocation = function(invocation);
142
143
/**
144
* Remove job from scheduled jobs registry (internal use)
145
*/
146
Job.prototype.deleteFromSchedule = function();
147
```
148
149
### Job Events
150
151
Jobs emit events throughout their lifecycle for monitoring and error handling.
152
153
```javascript { .api }
154
/**
155
* Emitted after each job execution starts
156
*/
157
job.on('run', function() {});
158
159
/**
160
* Emitted when job is scheduled with the fire date
161
* @param {Date} fireDate - When the job is scheduled to run
162
*/
163
job.on('scheduled', function(fireDate) {});
164
165
/**
166
* Emitted when a job invocation is canceled
167
* @param {Date} fireDate - When the canceled job was scheduled to run
168
*/
169
job.on('canceled', function(fireDate) {});
170
171
/**
172
* Emitted when job execution throws an error or returns a rejected Promise
173
* @param {Error} error - The error that occurred
174
*/
175
job.on('error', function(error) {});
176
177
/**
178
* Emitted when job execution completes successfully or returns a resolved Promise
179
* @param {*} result - The result returned by the job function
180
*/
181
job.on('success', function(result) {});
182
```
183
184
**Usage Examples:**
185
186
```javascript
187
const schedule = require('node-schedule');
188
189
// Create job with event handlers
190
const job = schedule.scheduleJob('*/10 * * * * *', function() {
191
// Job that might return a Promise
192
return new Promise((resolve, reject) => {
193
setTimeout(() => {
194
if (Math.random() > 0.7) {
195
reject(new Error('Random failure'));
196
} else {
197
resolve('Job completed successfully');
198
}
199
}, 1000);
200
});
201
});
202
203
// Handle events
204
job.on('run', () => {
205
console.log('Job started execution');
206
});
207
208
job.on('success', (result) => {
209
console.log('Job succeeded:', result);
210
});
211
212
job.on('error', (error) => {
213
console.error('Job failed:', error.message);
214
});
215
216
job.on('scheduled', (date) => {
217
console.log('Job scheduled for:', date);
218
});
219
220
job.on('canceled', (date) => {
221
console.log('Job canceled that was scheduled for:', date);
222
});
223
```
224
225
### Scheduled Jobs Registry
226
227
Global registry for managing named jobs across the application.
228
229
```javascript { .api }
230
/**
231
* Global object containing all named scheduled jobs
232
* Key is the job name, value is the Job instance
233
*/
234
const scheduledJobs: {[key: string]: Job};
235
```
236
237
**Usage Examples:**
238
239
```javascript
240
const { scheduleJob, scheduledJobs } = require('node-schedule');
241
242
// Create named jobs
243
scheduleJob('dailyReport', '0 9 * * *', function() {
244
console.log('Generating daily report...');
245
});
246
247
scheduleJob('weeklyCleanup', '0 2 * * 0', function() {
248
console.log('Running weekly cleanup...');
249
});
250
251
// Access jobs from registry
252
console.log('Active jobs:', Object.keys(scheduledJobs));
253
254
// Get specific job
255
const reportJob = scheduledJobs['dailyReport'];
256
console.log('Next report:', reportJob.nextInvocation());
257
258
// Cancel job by name
259
const success = cancelJob('weeklyCleanup');
260
console.log('Cleanup job canceled:', success);
261
```
262
263
### Promise Handling
264
265
Jobs can return Promises for asynchronous operations with proper success/error event handling.
266
267
**Usage Examples:**
268
269
```javascript
270
const schedule = require('node-schedule');
271
272
// Job that returns a Promise
273
const asyncJob = schedule.scheduleJob('*/30 * * * * *', async function() {
274
try {
275
const response = await fetch('https://api.example.com/data');
276
const data = await response.json();
277
return data; // Will trigger 'success' event with data
278
} catch (error) {
279
throw error; // Will trigger 'error' event
280
}
281
});
282
283
// Handle async results
284
asyncJob.on('success', (data) => {
285
console.log('API data received:', data);
286
});
287
288
asyncJob.on('error', (error) => {
289
console.error('API call failed:', error);
290
});
291
```
292
293
### Generator Function Support
294
295
Node Schedule automatically detects and handles JavaScript generator functions.
296
297
**Usage Examples:**
298
299
```javascript
300
const schedule = require('node-schedule');
301
302
// Job using a generator function
303
function* generatorJob() {
304
console.log('Generator job starting');
305
yield 'Step 1 complete';
306
yield 'Step 2 complete';
307
return 'Generator job finished';
308
}
309
310
const genJob = schedule.scheduleJob('*/30 * * * * *', generatorJob);
311
312
genJob.on('success', (result) => {
313
console.log('Generator job result:', result);
314
});
315
```
316
317
### Invocation Class
318
319
Internal class representing a scheduled job invocation. While primarily used internally, it's exported from the main module and accessible for advanced use cases.
320
321
```javascript { .api }
322
/**
323
* Create a job invocation (primarily for internal use)
324
* @param {Job} job - Associated job instance
325
* @param {Date} fireDate - When invocation should fire
326
* @param {RecurrenceRule} [recurrenceRule] - Associated recurrence rule
327
* @param {Date} [endDate] - Optional end date for recurring jobs
328
*/
329
class Invocation {
330
constructor(job, fireDate, recurrenceRule, endDate);
331
332
/** Associated job instance */
333
job: Job;
334
/** When invocation should fire */
335
fireDate: Date;
336
/** Associated recurrence rule */
337
recurrenceRule: RecurrenceRule;
338
/** Optional end date for recurring jobs */
339
endDate?: Date;
340
/** Internal timer identifier */
341
timerID: number | null;
342
}
343
```
344
345
**Usage Examples:**
346
347
```javascript
348
const { Invocation, Job, RecurrenceRule } = require('node-schedule');
349
350
// Typically used internally, but can be accessed if needed
351
const job = new Job('testJob', function() {
352
console.log('Job executed');
353
});
354
355
const rule = new RecurrenceRule();
356
rule.second = 30; // Every 30 seconds
357
358
// Internal invocation creation (normally handled automatically)
359
const fireDate = new Date(Date.now() + 5000); // 5 seconds from now
360
const invocation = new Invocation(job, fireDate, rule);
361
362
console.log('Invocation fire date:', invocation.fireDate);
363
console.log('Associated job:', invocation.job.name);
364
```