0
# Node Cron
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: node-cron
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install node-cron`
10
11
## Core Imports
12
13
```typescript
14
import cron from "node-cron";
15
```
16
17
Named imports:
18
19
```typescript
20
import { schedule, validate, getTasks, getTask, createTask, ScheduledTask, TaskFn, TaskContext, TaskOptions } from "node-cron";
21
```
22
23
For CommonJS:
24
25
```javascript
26
const cron = require("node-cron");
27
```
28
29
## Basic Usage
30
31
```typescript
32
import cron from "node-cron";
33
34
// Schedule a task to run every minute
35
const task = cron.schedule('* * * * *', () => {
36
console.log('Running every minute');
37
});
38
39
// Schedule a background task
40
const backgroundTask = cron.schedule('0 0 * * *', './tasks/daily-backup.js', {
41
timezone: 'America/New_York'
42
});
43
44
// Validate a cron expression
45
const isValid = cron.validate('0 0 * * *');
46
console.log(isValid); // true
47
48
// Control tasks
49
task.stop();
50
task.start();
51
task.destroy();
52
```
53
54
## Capabilities
55
56
### Task Scheduling
57
58
Core functionality for scheduling tasks using cron expressions.
59
60
```typescript { .api }
61
function schedule(
62
expression: string,
63
func: TaskFn | string,
64
options?: TaskOptions
65
): ScheduledTask;
66
```
67
68
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.
69
70
### Task Creation
71
72
Creates a task without immediately starting it.
73
74
```typescript { .api }
75
function createTask(
76
expression: string,
77
func: TaskFn | string,
78
options?: TaskOptions
79
): ScheduledTask;
80
```
81
82
**Note**: This is an internal function that is exported but primarily used by the `schedule` function.
83
84
### Expression Validation
85
86
Validates cron expressions to ensure correct syntax.
87
88
```typescript { .api }
89
function validate(expression: string): boolean;
90
```
91
92
Returns `true` if the cron expression is valid, `false` otherwise.
93
94
### Task Registry Management
95
96
Functions for managing scheduled tasks.
97
98
```typescript { .api }
99
function getTasks(): Map<string, ScheduledTask>;
100
function getTask(taskId: string): ScheduledTask | undefined;
101
```
102
103
`getTasks` returns all registered tasks, while `getTask` retrieves a specific task by its ID.
104
105
### Path Resolution (Internal)
106
107
Resolves file paths for background tasks.
108
109
```typescript { .api }
110
function solvePath(filePath: string): string;
111
```
112
113
**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.
114
115
## Task Management
116
117
### ScheduledTask Interface
118
119
All scheduled tasks implement the ScheduledTask interface for consistent task management.
120
121
```typescript { .api }
122
interface ScheduledTask {
123
id: string;
124
name?: string;
125
126
start(): void | Promise<void>;
127
stop(): void | Promise<void>;
128
getStatus(): string | Promise<string>;
129
destroy(): void | Promise<void>;
130
execute(): Promise<any>;
131
getNextRun(): Date | null;
132
133
on(event: TaskEvent, fun: (context: TaskContext) => Promise<void> | void): void;
134
off(event: TaskEvent, fun: (context: TaskContext) => Promise<void> | void): void;
135
once(event: TaskEvent, fun: (context: TaskContext) => Promise<void> | void): void;
136
}
137
```
138
139
### Task Status Values
140
141
The `getStatus()` method returns one of the following string values:
142
143
```typescript { .api }
144
type TaskStatus = 'stopped' | 'idle' | 'running' | 'destroyed';
145
```
146
147
- `'stopped'`: Task is created but not started, or has been manually stopped
148
- `'idle'`: Task is running and waiting for the next scheduled execution
149
- `'running'`: Task is currently executing
150
- `'destroyed'`: Task has been permanently destroyed and cannot be restarted
151
152
Example usage:
153
154
```typescript
155
const task = cron.schedule('* * * * *', () => {
156
console.log('Task running');
157
});
158
159
console.log(task.getStatus()); // 'idle'
160
task.stop();
161
console.log(task.getStatus()); // 'stopped'
162
task.destroy();
163
console.log(task.getStatus()); // 'destroyed'
164
```
165
166
### Task Events
167
168
Tasks emit events throughout their lifecycle for monitoring and debugging.
169
170
```typescript { .api }
171
type TaskEvent =
172
| 'task:started'
173
| 'task:stopped'
174
| 'task:destroyed'
175
| 'execution:started'
176
| 'execution:finished'
177
| 'execution:failed'
178
| 'execution:missed'
179
| 'execution:overlap'
180
| 'execution:maxReached';
181
```
182
183
Example event handling:
184
185
```typescript
186
const task = cron.schedule('* * * * *', () => {
187
console.log('Task executed');
188
});
189
190
task.on('execution:started', (context) => {
191
console.log('Task started at:', context.date);
192
});
193
194
task.on('execution:failed', (context) => {
195
console.error('Task failed:', context.execution?.error);
196
});
197
```
198
199
## Configuration Options
200
201
### TaskOptions
202
203
Configuration options for customizing task behavior.
204
205
```typescript { .api }
206
type TaskOptions = {
207
timezone?: string;
208
name?: string;
209
noOverlap?: boolean;
210
maxExecutions?: number;
211
maxRandomDelay?: number;
212
};
213
```
214
215
- `timezone`: Specify timezone for task execution (e.g., 'America/New_York')
216
- `name`: Custom name for the task (defaults to generated ID)
217
- `noOverlap`: Prevent overlapping executions if previous task is still running
218
- `maxExecutions`: Maximum number of times the task should execute
219
- `maxRandomDelay`: Add random delay (in ms) before execution
220
221
Example with options:
222
223
```typescript
224
const task = cron.schedule('0 9 * * *', () => {
225
console.log('Daily morning task');
226
}, {
227
timezone: 'Europe/London',
228
name: 'morning-routine',
229
noOverlap: true,
230
maxExecutions: 30
231
});
232
```
233
234
## Types and Context
235
236
### TaskFn
237
238
Function signature for inline task functions.
239
240
```typescript { .api }
241
type TaskFn = (context: TaskContext) => any | Promise<any>;
242
```
243
244
### TaskContext
245
246
Context object provided to task functions and event handlers.
247
248
```typescript { .api }
249
type TaskContext = {
250
date: Date;
251
dateLocalIso: string;
252
task?: ScheduledTask;
253
execution?: Execution;
254
triggeredAt: Date;
255
};
256
```
257
258
- `date`: The scheduled execution date (timezone-adjusted if specified)
259
- `dateLocalIso`: ISO 8601 formatted local date and time
260
- `task`: Reference to the scheduled task
261
- `execution`: Details about the current execution
262
- `triggeredAt`: Actual time the event was triggered
263
264
### Execution
265
266
Details about a specific task execution.
267
268
```typescript { .api }
269
type Execution = {
270
id: string;
271
reason: 'invoked' | 'scheduled';
272
startedAt?: Date;
273
finishedAt?: Date;
274
error?: Error;
275
result?: any;
276
};
277
```
278
279
## Cron Expression Format
280
281
Node-cron supports standard cron syntax with optional seconds field:
282
283
```
284
# ┌────────────── second (optional)
285
# │ ┌──────────── minute
286
# │ │ ┌────────── hour
287
# │ │ │ ┌──────── day of month
288
# │ │ │ │ ┌────── month
289
# │ │ │ │ │ ┌──── day of week
290
# │ │ │ │ │ │
291
# │ │ │ │ │ │
292
# * * * * * *
293
```
294
295
### Field Values
296
297
| field | value |
298
| ------------ | --------------------------------- |
299
| second | 0-59 |
300
| minute | 0-59 |
301
| hour | 0-23 |
302
| day of month | 1-31 |
303
| month | 1-12 (or names) |
304
| day of week | 0-7 (or names, 0 or 7 are sunday) |
305
306
### Common Examples
307
308
```typescript
309
// Every minute
310
cron.schedule('* * * * *', task);
311
312
// Every hour at minute 30
313
cron.schedule('30 * * * *', task);
314
315
// Daily at 2:30 AM
316
cron.schedule('30 2 * * *', task);
317
318
// Weekly on Sunday at midnight
319
cron.schedule('0 0 * * 0', task);
320
321
// Monthly on the 1st at midnight
322
cron.schedule('0 0 1 * *', task);
323
324
// With seconds: every 30 seconds
325
cron.schedule('*/30 * * * * *', task);
326
```
327
328
## Background Tasks
329
330
For background tasks, provide a file path instead of a function:
331
332
```typescript
333
// Background task file (./tasks/backup.js)
334
module.exports = (context) => {
335
console.log('Running backup at:', context.date);
336
// Perform backup operations
337
};
338
339
// Schedule the background task
340
const backgroundTask = cron.schedule('0 2 * * *', './tasks/backup.js');
341
```
342
343
Background tasks run in separate child processes, providing isolation from the main application.
344
345
## Error Handling
346
347
Tasks can handle errors through event listeners:
348
349
```typescript
350
const task = cron.schedule('* * * * *', () => {
351
throw new Error('Something went wrong');
352
});
353
354
task.on('execution:failed', (context) => {
355
console.error('Task failed:', context.execution?.error?.message);
356
357
// Optionally stop or restart the task
358
if (context.execution?.error?.message.includes('critical')) {
359
task.destroy();
360
}
361
});
362
```
363
364
## Manual Execution
365
366
Tasks can be executed manually regardless of their schedule:
367
368
```typescript
369
const task = cron.schedule('0 0 * * *', () => {
370
console.log('Daily task');
371
});
372
373
// Execute immediately
374
task.execute().then(result => {
375
console.log('Manual execution completed:', result);
376
}).catch(error => {
377
console.error('Manual execution failed:', error);
378
});
379
```