Skip to main content

@kreisler/js-cron

A TypeScript wrapper for node-cron that provides a clean API for managing scheduled tasks with advanced features like task lifecycle management, type-safe cron expression building, and timezone support.

Installation

npm install @kreisler/js-cron

Quick Start

import { JsCron } from '@kreisler/js-cron';

// Create a cron instance with timezone
const cron = new JsCron({ 
  timezone: 'America/Bogota',
  runOnInit: true 
});

// Create a task that runs every 10 seconds
const result = cron.createTask(
  'myTask',
  '*/10 * * * * *',
  () => console.log('Task executed!')
);

if (result.success) {
  console.log(result.message); // 'Tarea "myTask" creada con éxito.'
}

JsCron Class

Constructor

Create a new JsCron instance with optional configuration.
const cron = new JsCron(options);
options
ScheduleOptions
Configuration object for the cron instance:
timezone
string
Timezone for scheduling tasks (e.g., ‘America/New_York’, ‘Europe/London’, ‘Asia/Tokyo’)
runOnInit
boolean
default:"false"
Whether to run the task immediately upon creation
scheduled
boolean
default:"true"
Whether the task is scheduled to run
recoverMissedExecutions
boolean
default:"false"
Whether to execute missed tasks when the process starts
Example:
import { JsCron } from '@kreisler/js-cron';

const cron = new JsCron({
  timezone: 'America/New_York',
  runOnInit: false,
  scheduled: true
});

Task Management Methods

createTask()

Create and schedule a new task.
const result = cron.createTask(taskName, cronExpression, callback);
taskName
string
required
Unique name for the task. Used to identify and manage the task later.
cronExpression
string
required
Valid cron expression defining when the task should run.
callback
() => void
required
Function to execute when the task runs.
Returns: Object with success, message, and optionally task properties.
import { JsCron } from '@kreisler/js-cron';

const cron = new JsCron({ timezone: 'America/Bogota' });

// Execute every 15 minutes between 6:00 and 23:00
const result = cron.createTask(
  'dailyReport',
  '0 */15 6-23 * * *',
  () => {
    console.log('Generating daily report...');
    // Your task logic here
  }
);

if (!result.success) {
  console.error(result.message);
}
The createTask method validates the cron expression before creating the task. If the expression is invalid or a task with the same name already exists, it returns an error message.

destroyTask()

Stop and remove a task permanently.
const result = cron.destroyTask(taskName);
taskName
string
required
Name of the task to destroy
Returns: Object with success and message properties.
const result = cron.destroyTask('dailyReport');

if (result.success) {
  console.log(result.message); // 'Tarea "dailyReport" destruida con éxito.'
}

pauseTask()

Temporarily stop a task without removing it.
const result = cron.pauseTask(taskName);
taskName
string
required
Name of the task to pause
Returns: Object with success and message properties.
const result = cron.pauseTask('dailyReport');
console.log(result.message); // 'Tarea "dailyReport" pausada.'

resumeTask()

Resume a paused task.
const result = cron.resumeTask(taskName);
taskName
string
required
Name of the task to resume
Returns: Object with success and message properties.
const result = cron.resumeTask('dailyReport');
console.log(result.message); // 'Tarea "dailyReport" reanudada.'

Query Methods

getTasks()

Get all registered tasks.
const tasks = cron.getTasks();
Returns: Map<string, ScheduledTask> - Map of all tasks with their names as keys.
const tasks = cron.getTasks();

console.log(`Total tasks: ${tasks.size}`);

tasks.forEach((task, name) => {
  console.log(`Task: ${name}`);
});

getTask()

Get a specific task by name.
const task = cron.getTask(taskName);
taskName
string
required
Name of the task to retrieve
Returns: ScheduledTask | undefined - The task object or undefined if not found.
const task = cron.getTask('dailyReport');

if (task) {
  console.log('Task found!');
  // You can call task.start(), task.stop(), etc.
}

hasTask()

Check if a task exists.
const exists = cron.hasTask(taskName);
taskName
string
required
Name of the task to check
Returns: boolean - True if the task exists, false otherwise.
if (cron.hasTask('dailyReport')) {
  console.log('Task already exists!');
} else {
  cron.createTask('dailyReport', '0 9 * * *', () => {
    console.log('Running report...');
  });
}

Cron Expression Builder

The package includes a type-safe cron expression builder with IntelliSense support.

buildCronExpression()

Build cron expressions using a typed object instead of strings.
import { buildCronExpression } from '@kreisler/js-cron';

const expression = buildCronExpression({
  second: '0',
  minute: '*/15',
  hour: '6-23',
  dayOfMonth: '*',
  month: '*',
  dayOfWeek: '*',
  year: '*'
});

console.log(expression); // '0 */15 6-23 * * * *'

CronFields Interface

All fields are optional and default to *. The builder provides IntelliSense for valid values:
second
SecondType
Valid values: 0-59, *, ranges (e.g., 10-20), steps (e.g., */5), lists (e.g., 10,20,30)
// Examples
second: '0'        // At second 0
second: '*/10'     // Every 10 seconds
second: '0,30'     // At seconds 0 and 30
second: '10-20'    // Seconds 10 through 20

Cron Expression Format

Cron expressions consist of 7 fields:
┌───────────── second (0 - 59)
│ ┌───────────── minute (0 - 59)
│ │ ┌───────────── hour (0 - 23)
│ │ │ ┌───────────── day of month (1 - 31)
│ │ │ │ ┌───────────── month (1 - 12 or JAN-DEC)
│ │ │ │ │ ┌───────────── day of week (0 - 7 or SUN-SAT)
│ │ │ │ │ │ ┌───────────── year (1970 - 2099, optional)
│ │ │ │ │ │ │
* * * * * * *
Useful resources:

Common Patterns

// Every 10 seconds
cron.createTask('task1', '*/10 * * * * *', callback);

// Every 5 minutes
cron.createTask('task2', '0 */5 * * * *', callback);

// Every 2 hours
cron.createTask('task3', '0 0 */2 * * *', callback);
// Every 15 minutes from 6 AM to 11 PM
cron.createTask('business', '0 */15 6-23 * * *', callback);

// Every hour during business hours (9 AM - 5 PM)
cron.createTask('business2', '0 0 9-17 * * MON-FRI', callback);

// At 9 AM and 5 PM on weekdays
cron.createTask('business3', '0 0 9,17 * * 1-5', callback);
// Daily at 8:30 AM
cron.createTask('daily', '0 30 8 * * *', callback);

// Every Monday at 9 AM
cron.createTask('weekly', '0 0 9 * * MON', callback);

// First day of every month at midnight
cron.createTask('monthly', '0 0 0 1 * *', callback);

// Last day of every month at 11:59 PM
cron.createTask('monthEnd', '0 59 23 L * *', callback);
// Every quarter (Jan, Apr, Jul, Oct) at 1st day, 9 AM
cron.createTask('quarterly', '0 0 9 1 JAN,APR,JUL,OCT *', callback);

// Last Friday of every month at 5 PM
cron.createTask('lastFriday', '0 0 17 * * 5L', callback);

// Every weekday at 10 and 3
cron.createTask('weekday', '0 0 10,15 * * MON-FRI', callback);

Complete Example

import { JsCron, buildCronExpression } from '@kreisler/js-cron';

// Create cron instance
const cron = new JsCron({
  timezone: 'America/New_York',
  runOnInit: false
});

// Task 1: Health check every 30 seconds
const healthCheck = cron.createTask(
  'healthCheck',
  '*/30 * * * * *',
  () => {
    console.log('Performing health check...');
    // Check system health
  }
);

// Task 2: Daily report at 9 AM on weekdays
const dailyReportExpression = buildCronExpression({
  minute: '0',
  hour: '9',
  dayOfWeek: 'MON-FRI'
});

const dailyReport = cron.createTask(
  'dailyReport',
  dailyReportExpression,
  async () => {
    console.log('Generating daily report...');
    // Generate and send report
  }
);

// Task 3: Database cleanup on first day of month
const cleanup = cron.createTask(
  'dbCleanup',
  '0 0 2 1 * *', // 2 AM on 1st day of month
  async () => {
    console.log('Running database cleanup...');
    // Cleanup logic
  }
);

// Pause a task temporarily
setTimeout(() => {
  const result = cron.pauseTask('healthCheck');
  console.log(result.message);
  
  // Resume after 1 minute
  setTimeout(() => {
    cron.resumeTask('healthCheck');
  }, 60000);
}, 120000);

// List all tasks
console.log(`Active tasks: ${cron.getTasks().size}`);

// Graceful shutdown
process.on('SIGINT', () => {
  console.log('Stopping all tasks...');
  
  cron.getTasks().forEach((task, name) => {
    cron.destroyTask(name);
  });
  
  process.exit(0);
});

TypeScript Support

Full TypeScript support with type definitions for all methods and interfaces:
import type { 
  ScheduleOptions, 
  ScheduledTask,
  CronFields 
} from '@kreisler/js-cron';

// Type-safe configuration
const options: ScheduleOptions = {
  timezone: 'America/Los_Angeles',
  runOnInit: true
};

// Type-safe cron fields
const fields: CronFields = {
  second: '0',
  minute: '*/15',
  hour: '9-17',
  dayOfWeek: 'MON-FRI'
};

Error Handling

Always check the success property in the returned result objects:
const result = cron.createTask('myTask', '* * * * * *', callback);

if (!result.success) {
  console.error('Failed to create task:', result.message);
  // Handle error (invalid expression, duplicate name, etc.)
}
Common error scenarios:
  • Invalid cron expression: The expression doesn’t match the cron format
  • Task already exists: A task with the same name is already registered
  • Task not found: Attempting to operate on a non-existent task

License

MIT © Kreisler

Build docs developers (and LLMs) love