@bernierllc/cron-scheduler
v1.0.5
Published
Pure cron job scheduling utilities with advanced pattern parsing and validation
Downloads
62
Readme
@bernierllc/cron-scheduler
Pure cron job scheduling utilities with advanced pattern parsing and validation.
Installation
npm install @bernierllc/cron-schedulerFeatures
- Advanced Pattern Parsing: Comprehensive cron pattern validation with detailed error reporting
- Timezone Support: Schedule jobs in any timezone
- Job Management: Start, pause, stop, and monitor scheduled jobs
- Event System: Listen to job lifecycle events
- Fluent Builder: Create cron patterns using an intuitive API
- Time Constraints: Support for start/end times and maximum run counts
- Human Descriptions: Generate readable descriptions of cron patterns
Usage
Basic Scheduling
import { CronScheduler, JobStatus } from '@bernierllc/cron-scheduler';
const scheduler = new CronScheduler();
// Schedule a job
const jobInfo = scheduler.schedule(
'my-job',
'0 9 * * 1-5', // Monday to Friday at 9:00 AM
() => {
console.log('Good morning! Time to work.');
}
);
console.log(`Job ${jobInfo.id} scheduled for next run: ${jobInfo.nextRun}`);Advanced Job Options
scheduler.schedule(
'report-job',
'0 18 * * 5', // Every Friday at 6:00 PM
async () => {
await generateWeeklyReport();
},
{
timezone: 'America/New_York',
start: new Date('2024-01-01'),
end: new Date('2024-12-31'),
maxRuns: 52, // Run for one year
immediate: false
}
);Job Management
// Get job information
const jobInfo = scheduler.getJobInfo('my-job');
console.log(`Status: ${jobInfo.status}, Run count: ${jobInfo.runCount}`);
// Control jobs
scheduler.pause('my-job');
scheduler.start('my-job');
scheduler.stop('my-job');
// Get jobs by status
const runningJobs = scheduler.getJobsByStatus(JobStatus.RUNNING);
const allJobs = scheduler.getAllJobs();Fluent Schedule Builder
import { schedule } from '@bernierllc/cron-scheduler';
// Every 15 minutes
const pattern1 = schedule().every(15).minutes().build();
// Result: "0 */15 * * *"
// Daily at 9:30 AM
const pattern2 = schedule().at('9:30').daily().build();
// Result: "30 9 * * *"
// Weekly on Monday, Wednesday, Friday at 2:00 PM
const pattern3 = schedule()
.at('2:00 PM')
.on(['monday', 'wednesday', 'friday'])
.build();
// Result: "0 14 * * 1,3,5"
// Every 2 hours between 8 AM and 6 PM
const pattern4 = schedule()
.between('8:00', '18:00')
.every(2)
.hours()
.build();
// Result: "0 8-18 */2 * *"Pattern Validation
import { CronPatternParser, validation } from '@bernierllc/cron-scheduler';
// Validate a pattern
const result = CronPatternParser.validate('0 9 * * 1-5');
if (result.isValid) {
console.log('Pattern is valid');
} else {
console.log('Errors:', result.errors);
console.log('Warnings:', result.warnings);
}
// Quick validation helpers
console.log(validation.isValid('*/5 * * * *')); // true
console.log(validation.getErrors('60 * * * *')); // ['Value out of range...']Human-Readable Descriptions
import { ScheduleDescriptor } from '@bernierllc/cron-scheduler';
const description = ScheduleDescriptor.describe('0 9 * * 1-5');
console.log(description.summary); // "Runs daily at 9:00 AM on Monday-Friday"
console.log(description.detailed); // "This job runs daily at 9:00 AM on weekdays"Event Handling
// Listen to job events
scheduler.onJobEvent('my-job', (event) => {
console.log(`Job ${event.jobId}: ${event.type} at ${event.timestamp}`);
});
// Global error handler
scheduler.onError((error) => {
console.error('Job execution failed:', error);
});Common Patterns
import { commonPatterns } from '@bernierllc/cron-scheduler';
scheduler.schedule('backup', commonPatterns.dailyAt2AM, backupDatabase);
scheduler.schedule('cleanup', commonPatterns.weeklyMondayAt9AM, cleanupLogs);
scheduler.schedule('report', commonPatterns.monthlyFirstMondayAt9AM, generateReport);API Reference
CronScheduler
Main scheduler class for managing cron jobs.
Methods
schedule(id, pattern, callback, options?)- Schedule a new jobgetJobInfo(id)- Get information about a jobgetAllJobs()- Get all scheduled jobsgetJobsByStatus(status)- Get jobs by statusstart(id)- Start a paused jobpause(id)- Pause a running jobstop(id)- Stop and remove a jobstopAll()- Stop all jobsgetNextRun(pattern, timezone?)- Calculate next run timegetUpcomingRuns(pattern, count?, timezone?)- Get upcoming executionsonJobEvent(jobId, callback)- Listen to job eventsonError(handler)- Set global error handler
CronPatternParser
Static utilities for parsing and validating cron patterns.
Methods
parse(pattern)- Parse pattern into structured formatvalidate(pattern)- Validate pattern with error reportingnormalize(pattern)- Normalize pattern format
Schedule Builder
Fluent interface for building cron patterns.
Methods
every(interval)- Set interval frequencyat(time)- Set specific timeon(dayOrDate)- Set specific day/datebetween(start, end)- Set time rangebuild()- Generate cron pattern
Types
JobStatus
enum JobStatus {
SCHEDULED = 'scheduled',
RUNNING = 'running',
PAUSED = 'paused',
STOPPED = 'stopped',
COMPLETED = 'completed',
FAILED = 'failed'
}CronJobOptions
interface CronJobOptions {
timezone?: string;
start?: Date | string;
end?: Date | string;
maxRuns?: number;
immediate?: boolean;
runOnInit?: boolean;
}ScheduledJobInfo
interface ScheduledJobInfo {
id: string;
pattern: string;
nextRun: Date | null;
lastRun: Date | null;
runCount: number;
status: JobStatus;
timezone: string;
metadata?: Record<string, any>;
}Error Handling
The scheduler provides comprehensive error handling:
// Pattern validation errors
try {
scheduler.schedule('job', 'invalid-pattern', callback);
} catch (error) {
console.error('Invalid pattern:', error.message);
}
// Runtime errors
scheduler.onError(async (error) => {
await logError(error);
await notifyAdmin(error);
});Testing
npm test
npm run test:coverage
npm run test:watchLicense
Copyright (c) 2025 Bernier LLC. All rights reserved.
