npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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-scheduler

Features

  • 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 job
  • getJobInfo(id) - Get information about a job
  • getAllJobs() - Get all scheduled jobs
  • getJobsByStatus(status) - Get jobs by status
  • start(id) - Start a paused job
  • pause(id) - Pause a running job
  • stop(id) - Stop and remove a job
  • stopAll() - Stop all jobs
  • getNextRun(pattern, timezone?) - Calculate next run time
  • getUpcomingRuns(pattern, count?, timezone?) - Get upcoming executions
  • onJobEvent(jobId, callback) - Listen to job events
  • onError(handler) - Set global error handler

CronPatternParser

Static utilities for parsing and validating cron patterns.

Methods

  • parse(pattern) - Parse pattern into structured format
  • validate(pattern) - Validate pattern with error reporting
  • normalize(pattern) - Normalize pattern format

Schedule Builder

Fluent interface for building cron patterns.

Methods

  • every(interval) - Set interval frequency
  • at(time) - Set specific time
  • on(dayOrDate) - Set specific day/date
  • between(start, end) - Set time range
  • build() - 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:watch

License

Copyright (c) 2025 Bernier LLC. All rights reserved.