# Node Cron

Node Cron is a lightweight task scheduler for Node.js applications that enables scheduling and execution of tasks using full crontab syntax. It provides both CommonJS and ES6 module support with TypeScript definitions, allowing for flexible integration into any Node.js project.

## Package Information

- **Package Name**: node-cron
- **Package Type**: npm
- **Language**: TypeScript
- **Installation**: `npm install node-cron`

## Core Imports

```typescript
import cron from "node-cron";
```

Named imports:

```typescript
import { schedule, validate, getTasks, getTask, createTask, ScheduledTask, TaskFn, TaskContext, TaskOptions } from "node-cron";
```

For CommonJS:

```javascript
const cron = require("node-cron");
```

## Basic Usage

```typescript
import cron from "node-cron";

// Schedule a task to run every minute
const task = cron.schedule('* * * * *', () => {
  console.log('Running every minute');
});

// Schedule a background task
const backgroundTask = cron.schedule('0 0 * * *', './tasks/daily-backup.js', {
  timezone: 'America/New_York'
});

// Validate a cron expression
const isValid = cron.validate('0 0 * * *');
console.log(isValid); // true

// Control tasks
task.stop();
task.start();
task.destroy();
```

## Capabilities

### Task Scheduling

Core functionality for scheduling tasks using cron expressions.

```typescript { .api }
function schedule(
  expression: string, 
  func: TaskFn | string, 
  options?: TaskOptions
): ScheduledTask;
```

The `schedule` function creates and starts a task that executes according to the provided cron expression. It accepts either an inline function or a file path to a background task module.

### Task Creation

Creates a task without immediately starting it.

```typescript { .api }
function createTask(
  expression: string, 
  func: TaskFn | string, 
  options?: TaskOptions
): ScheduledTask;
```

**Note**: This is an internal function that is exported but primarily used by the `schedule` function.

### Expression Validation

Validates cron expressions to ensure correct syntax.

```typescript { .api }
function validate(expression: string): boolean;
```

Returns `true` if the cron expression is valid, `false` otherwise.

### Task Registry Management

Functions for managing scheduled tasks.

```typescript { .api }
function getTasks(): Map<string, ScheduledTask>;
function getTask(taskId: string): ScheduledTask | undefined;
```

`getTasks` returns all registered tasks, while `getTask` retrieves a specific task by its ID.

### Path Resolution (Internal)

Resolves file paths for background tasks.

```typescript { .api }
function solvePath(filePath: string): string;
```

**Note**: This is an internal utility function used by the scheduler to resolve task file paths. It's exported but not intended for direct use by library consumers.

## Task Management

### ScheduledTask Interface

All scheduled tasks implement the ScheduledTask interface for consistent task management.

```typescript { .api }
interface ScheduledTask {
  id: string;
  name?: string;
  
  start(): void | Promise<void>;
  stop(): void | Promise<void>;
  getStatus(): string | Promise<string>;
  destroy(): void | Promise<void>;
  execute(): Promise<any>;
  getNextRun(): Date | null;

  on(event: TaskEvent, fun: (context: TaskContext) => Promise<void> | void): void;
  off(event: TaskEvent, fun: (context: TaskContext) => Promise<void> | void): void;
  once(event: TaskEvent, fun: (context: TaskContext) => Promise<void> | void): void;
}
```

### Task Status Values

The `getStatus()` method returns one of the following string values:

```typescript { .api }
type TaskStatus = 'stopped' | 'idle' | 'running' | 'destroyed';
```

- `'stopped'`: Task is created but not started, or has been manually stopped
- `'idle'`: Task is running and waiting for the next scheduled execution
- `'running'`: Task is currently executing
- `'destroyed'`: Task has been permanently destroyed and cannot be restarted

Example usage:

```typescript
const task = cron.schedule('* * * * *', () => {
  console.log('Task running');
});

console.log(task.getStatus()); // 'idle'
task.stop();
console.log(task.getStatus()); // 'stopped'
task.destroy();
console.log(task.getStatus()); // 'destroyed'
```

### Task Events

Tasks emit events throughout their lifecycle for monitoring and debugging.

```typescript { .api }
type TaskEvent =
  | 'task:started'
  | 'task:stopped'
  | 'task:destroyed'
  | 'execution:started'
  | 'execution:finished'
  | 'execution:failed'
  | 'execution:missed'
  | 'execution:overlap'
  | 'execution:maxReached';
```

Example event handling:

```typescript
const task = cron.schedule('* * * * *', () => {
  console.log('Task executed');
});

task.on('execution:started', (context) => {
  console.log('Task started at:', context.date);
});

task.on('execution:failed', (context) => {
  console.error('Task failed:', context.execution?.error);
});
```

## Configuration Options

### TaskOptions

Configuration options for customizing task behavior.

```typescript { .api }
type TaskOptions = {
  timezone?: string;
  name?: string;
  noOverlap?: boolean;
  maxExecutions?: number;
  maxRandomDelay?: number;
};
```

- `timezone`: Specify timezone for task execution (e.g., 'America/New_York')
- `name`: Custom name for the task (defaults to generated ID)
- `noOverlap`: Prevent overlapping executions if previous task is still running
- `maxExecutions`: Maximum number of times the task should execute
- `maxRandomDelay`: Add random delay (in ms) before execution

Example with options:

```typescript
const task = cron.schedule('0 9 * * *', () => {
  console.log('Daily morning task');
}, {
  timezone: 'Europe/London',
  name: 'morning-routine',
  noOverlap: true,
  maxExecutions: 30
});
```

## Types and Context

### TaskFn

Function signature for inline task functions.

```typescript { .api }
type TaskFn = (context: TaskContext) => any | Promise<any>;
```

### TaskContext

Context object provided to task functions and event handlers.

```typescript { .api }
type TaskContext = {
  date: Date;
  dateLocalIso: string;
  task?: ScheduledTask;
  execution?: Execution;
  triggeredAt: Date;
};
```

- `date`: The scheduled execution date (timezone-adjusted if specified)
- `dateLocalIso`: ISO 8601 formatted local date and time
- `task`: Reference to the scheduled task
- `execution`: Details about the current execution
- `triggeredAt`: Actual time the event was triggered

### Execution

Details about a specific task execution.

```typescript { .api }
type Execution = {
  id: string;
  reason: 'invoked' | 'scheduled';
  startedAt?: Date;
  finishedAt?: Date;
  error?: Error;
  result?: any;
};
```

## Cron Expression Format

Node-cron supports standard cron syntax with optional seconds field:

```
# ┌────────────── second (optional)
# │ ┌──────────── minute
# │ │ ┌────────── hour
# │ │ │ ┌──────── day of month
# │ │ │ │ ┌────── month
# │ │ │ │ │ ┌──── day of week
# │ │ │ │ │ │
# │ │ │ │ │ │
# * * * * * *
```

### Field Values

| field        | value                             |
| ------------ | --------------------------------- |
| second       | 0-59                              |
| minute       | 0-59                              |
| hour         | 0-23                              |
| day of month | 1-31                              |
| month        | 1-12 (or names)                   |
| day of week  | 0-7 (or names, 0 or 7 are sunday) |

### Common Examples

```typescript
// Every minute
cron.schedule('* * * * *', task);

// Every hour at minute 30
cron.schedule('30 * * * *', task);

// Daily at 2:30 AM
cron.schedule('30 2 * * *', task);

// Weekly on Sunday at midnight
cron.schedule('0 0 * * 0', task);

// Monthly on the 1st at midnight
cron.schedule('0 0 1 * *', task);

// With seconds: every 30 seconds
cron.schedule('*/30 * * * * *', task);
```

## Background Tasks

For background tasks, provide a file path instead of a function:

```typescript
// Background task file (./tasks/backup.js)
module.exports = (context) => {
  console.log('Running backup at:', context.date);
  // Perform backup operations
};

// Schedule the background task
const backgroundTask = cron.schedule('0 2 * * *', './tasks/backup.js');
```

Background tasks run in separate child processes, providing isolation from the main application.

## Error Handling

Tasks can handle errors through event listeners:

```typescript
const task = cron.schedule('* * * * *', () => {
  throw new Error('Something went wrong');
});

task.on('execution:failed', (context) => {
  console.error('Task failed:', context.execution?.error?.message);
  
  // Optionally stop or restart the task
  if (context.execution?.error?.message.includes('critical')) {
    task.destroy();
  }
});
```

## Manual Execution

Tasks can be executed manually regardless of their schedule:

```typescript
const task = cron.schedule('0 0 * * *', () => {
  console.log('Daily task');
});

// Execute immediately
task.execute().then(result => {
  console.log('Manual execution completed:', result);
}).catch(error => {
  console.error('Manual execution failed:', error);
});
```