Skip to main content

@kreisler/js-cron

A powerful, type-safe wrapper around node-cron for creating and managing scheduled tasks with TypeScript support and advanced cron expression building.

Installation

npm install @kreisler/js-cron

Core Class

JsCron

Main class for managing cron tasks.

Constructor

options
ScheduleOptions
Configuration options for the cron scheduler.

Methods

createTask
Creates and schedules a new task.
taskName
string
required
Unique identifier for the task.
cronExpression
string
required
Cron expression defining when the task should run.
callback
() => void
required
Function to execute when the task runs.
return
{ success: boolean, message: string, task?: ScheduledTask }
Object containing:
  • success: Whether the task was created successfully
  • message: Descriptive message about the operation
  • task: The created ScheduledTask (if successful)
destroyTask
Stops and removes a task.
taskName
string
required
Name of the task to destroy.
return
{ success: boolean, message: string }
Result of the operation.
pauseTask
Temporarily stops a task without removing it.
taskName
string
required
Name of the task to pause.
return
{ success: boolean, message: string }
Result of the operation.
resumeTask
Resumes a paused task.
taskName
string
required
Name of the task to resume.
return
{ success: boolean, message: string }
Result of the operation.
getTasks
Retrieve all registered tasks.
return
Map<string, ScheduledTask>
Map of all tasks with task names as keys.
getTask
Retrieve a specific task.
taskName
string
required
Name of the task to retrieve.
return
ScheduledTask | undefined
The task if found, undefined otherwise.
hasTask
Check if a task exists.
taskName
string
required
Name of the task to check.
return
boolean
True if the task exists, false otherwise.

Utility Function

buildCronExpression

Builds a cron expression from a type-safe object with intelligent autocompletion.
cronFields
CronFields
required
Object defining the cron schedule.
return
string
Valid cron expression string.

Type Definitions

CronFields

interface CronFields {
  second?: SecondType
  minute?: MinuteType
  hour?: HourType
  dayOfMonth?: DayOfMonthType
  month?: MonthType
  dayOfWeek?: DayOfWeekType
  year?: YearType
}

Common Patterns

  • Minutes: '0,15,30,45', '0,30', '*/15'
  • Hours: '9,17', '0,12', '9,12,15', '*/6'
  • Days: 'MON-FRI', '1,15' (1st and 15th)
  • Months: 'JAN,APR,JUL,OCT', '*/3'

Usage Examples

Basic Task Creation

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

const cron = new JsCron()

// Run every 10 seconds
const result = cron.createTask(
  'myTask',
  '*/10 * * * * *',
  () => console.log('Task executed!')
)

if (result.success) {
  console.log(result.message)
}

Using buildCronExpression

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

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

// Every weekday at 9 AM
const expression = buildCronExpression({
  second: '0',
  minute: '0',
  hour: '9',
  dayOfWeek: 'MON-FRI'
})

cron.createTask('dailyReport', expression, () => {
  console.log('Generating daily report...')
})

Common Schedules

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

const cron = new JsCron()

// Every 15 minutes during business hours (6 AM - 11 PM)
const businessHours = buildCronExpression({
  second: '0',
  minute: '*/15',
  hour: '6-23'
})

cron.createTask('checkStatus', businessHours, () => {
  console.log('Checking system status...')
})

// Every hour on the hour
const hourly = buildCronExpression({
  second: '0',
  minute: '0'
})

cron.createTask('hourlyTask', hourly, () => {
  console.log('Hourly maintenance')
})

// First day of every month at midnight
const monthly = buildCronExpression({
  second: '0',
  minute: '0',
  hour: '0',
  dayOfMonth: '1'
})

cron.createTask('monthlyReport', monthly, () => {
  console.log('Generating monthly report')
})

Task Management

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

const cron = new JsCron()

cron.createTask('task1', '*/5 * * * * *', () => console.log('Task 1'))
cron.createTask('task2', '*/10 * * * * *', () => console.log('Task 2'))

// List all tasks
console.log('Total tasks:', cron.getTasks().size)

// Check if task exists
if (cron.hasTask('task1')) {
  console.log('Task 1 is registered')
}

// Pause a task
cron.pauseTask('task1')

// Resume a task
setTimeout(() => {
  cron.resumeTask('task1')
}, 10000)

// Destroy a task
cron.destroyTask('task2')

Advanced Cron Expressions

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

// Every quarter hour (0, 15, 30, 45 minutes)
const quarterHourly = buildCronExpression({
  minute: '0,15,30,45'
})

// Business hours (9 AM - 5 PM) on weekdays
const businessDay = buildCronExpression({
  hour: '9-17',
  dayOfWeek: 'MON-FRI'
})

// Last day of every month
const lastDayOfMonth = buildCronExpression({
  dayOfMonth: 'L'
})

// Every 3rd Friday of the month at 10 AM
const thirdFriday = buildCronExpression({
  hour: '10',
  minute: '0',
  dayOfWeek: '6#3' // Friday (#3 = third occurrence)
})

// Quarterly (January, April, July, October)
const quarterly = buildCronExpression({
  dayOfMonth: '1',
  month: 'JAN,APR,JUL,OCT',
  hour: '0',
  minute: '0'
})

Database Backup Example

import { JsCron, buildCronExpression } from '@kreisler/js-cron'
import { execPromise } from '@kreisler/exec-promise'

const cron = new JsCron({ timezone: 'UTC' })

// Daily backup at 2 AM
const backupSchedule = buildCronExpression({
  second: '0',
  minute: '0',
  hour: '2'
})

cron.createTask('dailyBackup', backupSchedule, async () => {
  console.log('Starting database backup...')
  try {
    await execPromise('pg_dump mydb > backup.sql')
    console.log('Backup completed successfully')
  } catch (error) {
    console.error('Backup failed:', error)
  }
})

API Health Check

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

const cron = new JsCron()

// Check every 30 seconds
cron.createTask('healthCheck', '*/30 * * * * *', async () => {
  try {
    const response = await fetch('https://api.example.com/health')
    if (response.ok) {
      console.log('API is healthy')
    } else {
      console.warn('API returned non-OK status:', response.status)
    }
  } catch (error) {
    console.error('API health check failed:', error)
  }
})

Email Digest

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

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

// Send digest every Monday at 8 AM
const weeklyDigest = buildCronExpression({
  second: '0',
  minute: '0',
  hour: '8',
  dayOfWeek: 'MON'
})

cron.createTask('weeklyDigest', weeklyDigest, async () => {
  console.log('Generating weekly digest...')
  // Email sending logic here
})

Cache Cleanup

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

const cron = new JsCron()

// Clean cache every 6 hours
const cleanupSchedule = buildCronExpression({
  hour: '*/6',
  minute: '0',
  second: '0'
})

cron.createTask('cacheCleanup', cleanupSchedule, () => {
  console.log('Cleaning expired cache entries...')
  // Cache cleanup logic
})

Cron Expression Format

Cron expressions consist of 6-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 (optional, 1970-2099)
│ │ │ │ │ │ │
* * * * * * *

Special Characters

  • * - Any value
  • , - Value list separator
  • - - Range of values
  • / - Step values
  • ? - No specific value (day fields only)
  • L - Last (day of month/week)
  • W - Weekday
  • # - Nth occurrence (e.g., 6#3 = 3rd Friday)

Helpful Resources

Best Practices

  • Use descriptive task names
  • Handle errors within task callbacks
  • Set appropriate timezones for scheduled tasks
  • Clean up tasks when they’re no longer needed
  • Use buildCronExpression for type safety
  • Test cron expressions before deployment

Build docs developers (and LLMs) love