or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.mdjob-management.mdtime-calculations.md
tile.json

job-management.mddocs/

Job Management

Core job scheduling and lifecycle management functionality for creating, starting, stopping, and monitoring cron jobs with comprehensive configuration options and error handling.

Capabilities

CronJob Class

Main class for creating and managing scheduled jobs with full lifecycle control.

/**
 * Main class for creating and managing cron jobs
 * @template OC - Type of onComplete callback command (null if not provided)
 * @template C - Type of execution context (null if not provided)
 */
class CronJob<OC extends CronOnCompleteCommand | null = null, C = null> {
  // Constructor overloads for timezone/utcOffset exclusivity
  constructor(
    cronTime: string | Date | DateTime,
    onTick: CronCommand<C, WithOnComplete<OC>>,
    onComplete?: OC,
    start?: boolean | null,
    timeZone?: string | null,
    context?: C,
    runOnInit?: boolean | null,
    utcOffset?: never,
    unrefTimeout?: boolean | null,
    waitForCompletion?: boolean | null,
    errorHandler?: ((error: unknown) => void) | null,
    name?: string | null,
    threshold?: number | null
  );
  
  constructor(
    cronTime: string | Date | DateTime,
    onTick: CronCommand<C, WithOnComplete<OC>>,
    onComplete?: OC,
    start?: boolean | null,
    timeZone?: never,
    context?: C,
    runOnInit?: boolean | null,
    utcOffset?: number | null,
    unrefTimeout?: boolean | null,
    waitForCompletion?: boolean | null,
    errorHandler?: ((error: unknown) => void) | null,
    name?: string | null,
    threshold?: number | null
  );

  constructor(
    cronTime: string | Date | DateTime,
    onTick: CronCommand<C, WithOnComplete<OC>>,
    onComplete?: OC,
    start?: boolean | null,
    timeZone?: string | null,
    context?: C,
    runOnInit?: boolean | null,
    utcOffset?: number | null,
    unrefTimeout?: boolean | null,
    waitForCompletion?: boolean | null,
    errorHandler?: ((error: unknown) => void) | null,
    name?: string | null,
    threshold?: number | null
  );

  // Properties (read-only getters)
  readonly isActive: boolean;
  readonly isCallbackRunning: boolean;
  
  // Public properties
  cronTime: CronTime;
  lastExecution: Date | null;
  context: CronContext<C>;
  unrefTimeout: boolean;
  runOnce: boolean;
  waitForCompletion: boolean;
  errorHandler?: ((error: unknown) => void);
  name?: string;
  threshold: number;

  // Static factory method
  static from<OC extends CronOnCompleteCommand | null = null, C = null>(
    params: CronJobParams<OC, C>
  ): CronJob<OC, C>;

  // Instance methods
  start(): void;
  stop(): void | Promise<void>;
  setTime(time: CronTime): void;
  nextDate(): DateTime;
  nextDates(count?: number): DateTime | DateTime[];
  lastDate(): Date | null;
  fireOnTick(): Promise<void>;
  addCallback(callback: CronCallback<C, WithOnComplete<OC>>): void;
}

Constructor Parameters:

  • cronTime - The time to fire the job. Can be cron syntax, JS Date, or Luxon DateTime
  • onTick - Function to execute at the specified time. Receives onComplete as argument if provided
  • onComplete - Optional callback invoked when job is stopped or after onTick completes
  • start - Whether to start the job immediately. Default: false
  • timeZone - Execution timezone (e.g., 'America/Los_Angeles'). Cannot be used with utcOffset
  • context - Execution context for the onTick method
  • runOnInit - Execute onTick immediately after job creation. Default: false
  • utcOffset - Timezone offset in minutes. Cannot be used with timeZone
  • unrefTimeout - Unref the timeout to allow process to exit. Default: false
  • waitForCompletion - Skip executions if previous callback is still running. Default: false
  • errorHandler - Function to handle exceptions in onTick
  • name - Optional job name for identification and logging
  • threshold - Threshold in ms for handling missed executions. Default: 250

Usage Examples:

import { CronJob } from "cron";

// Basic cron job with function callback
const simpleJob = new CronJob(
  '0 0 * * *', // midnight every day
  function() {
    console.log('Daily backup started');
  },
  null, // no onComplete
  true  // start immediately
);

// Job with completion callback and error handling
const advancedJob = new CronJob(
  '*/5 * * * *', // every 5 minutes
  async function(onComplete) {
    try {
      await performAsyncTask();
      console.log('Task completed successfully');
      if (onComplete) onComplete();
    } catch (error) {
      console.error('Task failed:', error);
    }
  },
  function() {
    console.log('Job stopped or completed');
  },
  false, // don't start automatically
  'UTC', // timezone
  null,  // no custom context
  false, // don't run on init
  null,  // no utc offset
  false, // don't unref timeout
  true,  // wait for completion
  (error) => console.error('Job error:', error), // error handler
  'backup-job', // job name
  1000   // 1 second threshold
);

// Job with system command
const commandJob = new CronJob(
  '0 2 * * 0', // 2 AM every Sunday
  'ls -la /backup',
  null,
  true
);

// Job with complex system command
const complexCommandJob = new CronJob(
  '0 0 * * *',
  {
    command: 'rsync',
    args: ['-av', '/source/', '/backup/'],
    options: { stdio: 'inherit' }
  },
  null,
  true
);

Static Factory Method

Alternative constructor using object parameters for better readability.

/**
 * Create CronJob from parameters object
 * @param params - Configuration object with job parameters
 * @returns New CronJob instance
 */
static from<OC extends CronOnCompleteCommand | null = null, C = null>(
  params: CronJobParams<OC, C>
): CronJob<OC, C>;

Usage Examples:

// Using from() method with object parameters
const job = CronJob.from({
  cronTime: '0 0 * * *',
  onTick: function() {
    console.log('Daily task executed');
  },
  start: true,
  timeZone: 'America/New_York',
  name: 'daily-maintenance',
  errorHandler: (error) => console.error('Job failed:', error)
});

// With custom context
interface TaskContext {
  taskId: string;
  retryCount: number;
}

const contextJob = CronJob.from({
  cronTime: '*/10 * * * *',
  onTick: function() {
    console.log(`Executing task ${this.taskId}, attempt ${this.retryCount}`);
  },
  context: { taskId: 'backup-001', retryCount: 1 },
  start: true
});

Job Control Methods

Methods for controlling job execution lifecycle.

/**
 * Start the cron job
 * Initiates the scheduling and begins waiting for the next execution time
 */
start(): void;

/**
 * Stop the cron job
 * If waitForCompletion is true, returns Promise that resolves after current callback completes
 * @returns void or Promise<void> depending on waitForCompletion setting
 */
stop(): void | Promise<void>;

/**
 * Update the job's schedule
 * @param time - New CronTime instance with updated schedule
 */
setTime(time: CronTime): void;

/**
 * Manually trigger the job callback
 * Executes onTick without waiting for scheduled time
 */
fireOnTick(): Promise<void>;

/**
 * Add additional callback function
 * @param callback - Additional callback to execute on job tick
 */
addCallback(callback: CronCallback<C, WithOnComplete<OC>>): void;

Usage Examples:

const job = new CronJob('0 0 * * *', () => {
  console.log('Scheduled task');
}, null, false); // don't start automatically

// Manual control
job.start();
console.log('Job started:', job.isActive); // true

// Update schedule
const newTime = new CronTime('0 12 * * *'); // change to noon
job.setTime(newTime);

// Add additional callback
job.addCallback(() => {
  console.log('Additional task executed');
});

// Manual execution
await job.fireOnTick();

// Stop job
await job.stop();
console.log('Job stopped:', job.isActive); // false

Job Information Methods

Methods for retrieving job execution information.

/**
 * Get next execution date
 * @returns Luxon DateTime object for next execution
 */
nextDate(): DateTime;

/**
 * Get multiple next execution dates
 * @param count - Number of future dates to return
 * @returns Single DateTime or array of DateTime objects
 */
nextDates(count?: number): DateTime | DateTime[];

/**
 * Get last execution date
 * @returns Date of last execution or null if never executed
 */
lastDate(): Date | null;

Usage Examples:

const job = new CronJob('0 0 * * *', () => {}, null, true);

// Get next execution
const next = job.nextDate();
console.log('Next execution:', next.toISO());

// Get multiple future executions
const nextFive = job.nextDates(5) as DateTime[];
nextFive.forEach((date, i) => {
  console.log(`Execution ${i + 1}:`, date.toISO());
});

// Check last execution
const last = job.lastDate();
if (last) {
  console.log('Last executed:', last.toISOString());
} else {
  console.log('Never executed');
}

Job Properties

Read-only properties providing job state information.

// Job state properties
readonly isActive: boolean;           // Whether job is currently scheduled
readonly isCallbackRunning: boolean;  // Whether callback is currently executing
readonly lastExecution: Date | null;  // Date of last execution

// Configuration properties
readonly cronTime: CronTime;          // CronTime instance managing schedule
readonly context: CronContext<C>;     // Execution context
readonly unrefTimeout: boolean;       // Whether timeout is unreferenced
readonly runOnce: boolean;           // Whether job runs only once (for Date/DateTime)
readonly waitForCompletion: boolean;  // Whether to wait for callback completion
readonly errorHandler?: ((error: unknown) => void); // Error handling function
readonly name?: string;              // Optional job name
readonly threshold: number;          // Threshold for missed execution handling

Usage Examples:

const job = new CronJob('* * * * * *', async () => {
  console.log('Callback running:', job.isCallbackRunning); // true during execution
  await new Promise(resolve => setTimeout(resolve, 1000));
}, null, true, null, null, false, null, false, true); // waitForCompletion: true

console.log('Job active:', job.isActive);               // true
console.log('Callback running:', job.isCallbackRunning); // false initially
console.log('Threshold:', job.threshold);               // 250 (default)
console.log('Wait for completion:', job.waitForCompletion); // true