A cron-like and not-cron-like job scheduler for Node.js with flexible recurrence rules and time-based scheduling.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Advanced job management capabilities for controlling job lifecycle, handling events, and managing job state in Node Schedule.
The Job class represents a scheduled task and extends EventEmitter for lifecycle event handling.
/**
* Create a new job instance
* @param {string} [name] - Optional job name
* @param {function} job - Function to execute when job fires
* @param {function} [callback] - Optional callback executed after job completion
*/
class Job extends EventEmitter {
constructor(name?, job, callback?);
/** Job name (readonly) */
readonly name: string;
/** Job function to execute */
job: function;
/** Optional callback function */
callback: function | false;
/** Number of currently running invocations */
running: number;
/** Array of pending invocation objects */
pendingInvocations: Invocation[];
/** Whether this is a one-time job */
isOneTimeJob: boolean;
}Usage Examples:
const { Job } = require('node-schedule');
// Create a job manually
const job = new Job('myJob', function(fireDate) {
console.log('Job executed at:', fireDate);
});
// Schedule the job
job.schedule('*/5 * * * *'); // Every 5 minutes
// Listen for events
job.on('run', () => console.log('Job started'));
job.on('success', (result) => console.log('Job completed:', result));
job.on('error', (err) => console.error('Job failed:', err));Methods for scheduling and rescheduling jobs with various timing specifications.
/**
* Schedule the job with a timing specification
* @param {string|Date|object} spec - Schedule specification
* @returns {boolean} True if scheduling succeeded
*/
Job.prototype.schedule = function(spec);
/**
* Reschedule the job with new timing
* @param {string|Date|object} spec - New schedule specification
* @returns {boolean} True if rescheduling succeeded
*/
Job.prototype.reschedule = function(spec);
/**
* Schedule job to run on a specific date (alias for schedule)
* @param {Date} date - Date to run the job
* @returns {boolean} True if scheduling succeeded
*/
Job.prototype.runOnDate = function(date);Methods for controlling job execution and lifecycle.
/**
* Cancel all pending invocations of the job
* @param {boolean} [reschedule=false] - Whether to reschedule recurring jobs
* @returns {boolean} True if cancellation succeeded
*/
Job.prototype.cancel = function(reschedule);
/**
* Cancel only the next pending invocation
* @param {boolean} [reschedule=true] - Whether to reschedule the next occurrence
* @returns {boolean} True if cancellation succeeded
*/
Job.prototype.cancelNext = function(reschedule);
/**
* Manually invoke the job function
* @param {Date} [fireDate] - Date to pass to the job function
* @returns {*} Result of the job function
*/
Job.prototype.invoke = function(fireDate);Methods for inspecting job state and scheduling information.
/**
* Get the date of the next scheduled invocation
* @returns {Date|null} Next invocation date or null if no pending invocations
*/
Job.prototype.nextInvocation = function();
/**
* Get the total number of times this job has been triggered
* @returns {number} Count of triggered jobs
*/
Job.prototype.triggeredJobs = function();
/**
* Set the total number of times this job has been triggered
* @param {number} count - New triggered jobs count
*/
Job.prototype.setTriggeredJobs = function(count);
/**
* Track a new invocation (internal use)
* @param {Invocation} invocation - Invocation to track
*/
Job.prototype.trackInvocation = function(invocation);
/**
* Stop tracking an invocation (internal use)
* @param {Invocation} invocation - Invocation to stop tracking
*/
Job.prototype.stopTrackingInvocation = function(invocation);
/**
* Remove job from scheduled jobs registry (internal use)
*/
Job.prototype.deleteFromSchedule = function();Jobs emit events throughout their lifecycle for monitoring and error handling.
/**
* Emitted after each job execution starts
*/
job.on('run', function() {});
/**
* Emitted when job is scheduled with the fire date
* @param {Date} fireDate - When the job is scheduled to run
*/
job.on('scheduled', function(fireDate) {});
/**
* Emitted when a job invocation is canceled
* @param {Date} fireDate - When the canceled job was scheduled to run
*/
job.on('canceled', function(fireDate) {});
/**
* Emitted when job execution throws an error or returns a rejected Promise
* @param {Error} error - The error that occurred
*/
job.on('error', function(error) {});
/**
* Emitted when job execution completes successfully or returns a resolved Promise
* @param {*} result - The result returned by the job function
*/
job.on('success', function(result) {});Usage Examples:
const schedule = require('node-schedule');
// Create job with event handlers
const job = schedule.scheduleJob('*/10 * * * * *', function() {
// Job that might return a Promise
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.7) {
reject(new Error('Random failure'));
} else {
resolve('Job completed successfully');
}
}, 1000);
});
});
// Handle events
job.on('run', () => {
console.log('Job started execution');
});
job.on('success', (result) => {
console.log('Job succeeded:', result);
});
job.on('error', (error) => {
console.error('Job failed:', error.message);
});
job.on('scheduled', (date) => {
console.log('Job scheduled for:', date);
});
job.on('canceled', (date) => {
console.log('Job canceled that was scheduled for:', date);
});Global registry for managing named jobs across the application.
/**
* Global object containing all named scheduled jobs
* Key is the job name, value is the Job instance
*/
const scheduledJobs: {[key: string]: Job};Usage Examples:
const { scheduleJob, scheduledJobs } = require('node-schedule');
// Create named jobs
scheduleJob('dailyReport', '0 9 * * *', function() {
console.log('Generating daily report...');
});
scheduleJob('weeklyCleanup', '0 2 * * 0', function() {
console.log('Running weekly cleanup...');
});
// Access jobs from registry
console.log('Active jobs:', Object.keys(scheduledJobs));
// Get specific job
const reportJob = scheduledJobs['dailyReport'];
console.log('Next report:', reportJob.nextInvocation());
// Cancel job by name
const success = cancelJob('weeklyCleanup');
console.log('Cleanup job canceled:', success);Jobs can return Promises for asynchronous operations with proper success/error event handling.
Usage Examples:
const schedule = require('node-schedule');
// Job that returns a Promise
const asyncJob = schedule.scheduleJob('*/30 * * * * *', async function() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data; // Will trigger 'success' event with data
} catch (error) {
throw error; // Will trigger 'error' event
}
});
// Handle async results
asyncJob.on('success', (data) => {
console.log('API data received:', data);
});
asyncJob.on('error', (error) => {
console.error('API call failed:', error);
});Node Schedule automatically detects and handles JavaScript generator functions.
Usage Examples:
const schedule = require('node-schedule');
// Job using a generator function
function* generatorJob() {
console.log('Generator job starting');
yield 'Step 1 complete';
yield 'Step 2 complete';
return 'Generator job finished';
}
const genJob = schedule.scheduleJob('*/30 * * * * *', generatorJob);
genJob.on('success', (result) => {
console.log('Generator job result:', result);
});Internal class representing a scheduled job invocation. While primarily used internally, it's exported from the main module and accessible for advanced use cases.
/**
* Create a job invocation (primarily for internal use)
* @param {Job} job - Associated job instance
* @param {Date} fireDate - When invocation should fire
* @param {RecurrenceRule} [recurrenceRule] - Associated recurrence rule
* @param {Date} [endDate] - Optional end date for recurring jobs
*/
class Invocation {
constructor(job, fireDate, recurrenceRule, endDate);
/** Associated job instance */
job: Job;
/** When invocation should fire */
fireDate: Date;
/** Associated recurrence rule */
recurrenceRule: RecurrenceRule;
/** Optional end date for recurring jobs */
endDate?: Date;
/** Internal timer identifier */
timerID: number | null;
}Usage Examples:
const { Invocation, Job, RecurrenceRule } = require('node-schedule');
// Typically used internally, but can be accessed if needed
const job = new Job('testJob', function() {
console.log('Job executed');
});
const rule = new RecurrenceRule();
rule.second = 30; // Every 30 seconds
// Internal invocation creation (normally handled automatically)
const fireDate = new Date(Date.now() + 5000); // 5 seconds from now
const invocation = new Invocation(job, fireDate, rule);
console.log('Invocation fire date:', invocation.fireDate);
console.log('Associated job:', invocation.job.name);