Skip to content

Listening to Task Events

Scheduled tasks — both basic and background — support lifecycle event subscriptions through the .on(), .once(), and .off() methods.

These events let you react to key moments in a task’s lifecycle, such as when it starts, finishes, fails, or is destroyed. Every listener receives a TaskContext object containing detailed metadata about the task and its execution.

Available Events

EventPayloadDescription
task:startedTaskContextEmitted when the task is started via .start().
task:stoppedTaskContextEmitted when the task is stopped via .stop().
task:destroyedTaskContextEmitted when the task is destroyed via .destroy().
execution:startedTaskContextEmitted right before the task callback is executed.
execution:finishedTaskContextEmitted after the task successfully finishes.
execution:failedTaskContextEmitted when the task throws an error.
execution:missedTaskContextEmitted when a scheduled execution is missed.
execution:overlapTaskContextEmitted when a scheduled execution is skipped due to an ongoing one.
execution:maxReachedTaskContextEmitted when maxExecutions is reached. The task is destroyed.

Example

js
const task = cron.schedule('* * * * *', async (context) => {
  console.log('Running task at', context.date);
  return 'done';
});

task.on('execution:started', (ctx) => {
  console.log('Execution started at', ctx.date, 'Reason:', ctx.execution?.reason);
});

task.on('execution:finished', (ctx) => {
  console.log('Execution finished. Result:', ctx.execution?.result);
});

task.on('execution:failed', (ctx) => {
  console.error('Execution failed with error:', ctx.execution?.error?.message);
});

task.on('execution:maxReached', (ctx) => {
  console.warn(`Task "${ctx.task?.id}" reached max executions.`);
});

TaskContext Payload

Every event now provides a TaskContext object for consistent access to timing and execution metadata.

Type Definition

ts
export type TaskContext = {
  date: Date;
  dateLocalIso: string;
  triggeredAt: Date;
  task?: ScheduledTask;
  execution?: Execution;
}

Field Descriptions

FieldTypeDescription
dateDateTimestamp when the task was scheduled to run (or did run).
dateLocalIsostringHuman-readable local timestamp string, using the provided timezone.
triggeredAtDateActual time the event was emitted. Useful for debugging latency or drift.
taskScheduledTaskReference to the task instance.
executionExecution?Execution info if relevant to the event (null for non-execution events).

Execution Type

This structure is embedded in TaskContext.execution and represents a single run of a task:

js
export type Execution = {
  id: string;
  reason: 'invoked' | 'scheduled';
  startedAt?: Date;
  finishedAt?: Date;
  error?: Error;
  result?: any;
}

Execution Fields

FieldTypeDescription
idstringUnique ID for this execution.
reasonstringWhy the task was triggered — either 'invoked' or 'scheduled'.
startedAtDate?Time execution started.
finishedAtDate?Time execution finished.
errorError?Error thrown, if any.
resultany?Return value of the task if successful.

Notes

  • All event listeners receive a TaskContext, even for events like task:stopped or execution:missed.
  • Always attach listeners before calling .start() to avoid missing early events.
  • Background tasks emit the same events with the same context, relayed from the worker process.

Released in 2016 under the ISC License.