UNPKG

10.9 kBMarkdownView Raw
1<p align="center">
2 <img src="logo.svg" alt="cron for Node.js logo" height="150">
3 <br />
4 <b>cron</b> is a robust tool for running jobs (functions or commands) on schedules defined using the cron syntax.
5 <br />
6 Perfect for tasks like data backups, notifications, and many more!
7</p>
8
9# Cron for Node.js
10
11[![Version](https://img.shields.io/npm/v/cron?label=version&logo=npm)](https://www.npmjs.com/package/cron)
12[![Monthly Downloads](https://img.shields.io/npm/dm/cron?logo=npm)](https://www.npmjs.com/package/cron)
13[![Build Status](https://img.shields.io/github/actions/workflow/status/kelektiv/node-cron/release.yml?logo=github)](https://github.com/kelektiv/node-cron/actions/workflows/release.yml)
14[![CodeQL Status](https://img.shields.io/github/actions/workflow/status/kelektiv/node-cron/codeql.yml?logo=github&label=CodeQL)](https://github.com/kelektiv/node-cron/actions/workflows/codeql.yml)
15[![Coverage](https://img.shields.io/codecov/c/gh/kelektiv/node-cron?logo=codecov)](https://app.codecov.io/gh/kelektiv/node-cron)
16[![Renovate](https://img.shields.io/badge/renovate-enabled-dark_green)](https://github.com/kelektiv/node-cron/issues/718)
17[![OpenSSF Scorecard](https://img.shields.io/ossf-scorecard/github.com/kelektiv/node-cron?label=openssf%20scorecard)](https://securityscorecards.dev/viewer/?uri=github.com/kelektiv/node-cron)
18[![Discord](https://img.shields.io/discord/1075597081017851934?logo=discord)](https://discord.gg/yyKns29zch)
19
20## 🌟 Features
21
22- execute a function whenever your scheduled job triggers
23- execute a job external to the javascript process (like a system command) using `child_process`
24- use a Date or Luxon DateTime object instead of cron syntax as the trigger for your callback
25- use an additional slot for seconds (leaving it off will default to 0 and match the Unix behavior)
26
27## 🚀 Installation
28
29```bash
30npm install cron
31```
32
33## Table of Contents
34
351. [Features](#-features)
362. [Installation](#-installation)
373. [Migrating from v2 to v3](#-migrating-from-v2-to-v3)
384. [Basic Usage](#-basic-usage)
395. [Cron Patterns](#cron-patterns)
40 - [Cron Syntax Overview](#cron-patterns)
41 - [Supported Ranges](#supported-ranges)
426. [Gotchas](#gotchas)
437. [API](#api)
44 - [Standalone Functions](#standalone-functions)
45 - [CronJob Class](#cronjob-class)
46 - [CronTime Class](#crontime-class)
478. [Community](#-community)
48 - [Join the Community](#-community)
499. [Contributing](#-contributing)
50 - [General Contribution](#-contributing)
51 - [Submitting Bugs/Issues](#-submitting-bugsissues)
5210. [Acknowledgements](#-acknowledgements)
5311. [License](#license)
54
55## 🔄 Migrating from v2 to v3
56
57With the introduction of TypeScript in version 3 and alignment with UNIX cron patterns, a few changes have been made:
58
59<details>
60 <summary>Migrating from v2 to v3</summary>
61
62### Month & day-of-week indexing changes
63
64- **Month Indexing:** Changed from `0-11` to `1-12`. So you need to increment all numeric months by 1.
65
66- **Day-of-Week Indexing:** Support added for `7` as Sunday.
67
68### Adjustments in `CronJob`
69
70- The constructor no longer accepts an object as its first and only params. Use `CronJob.from(argsObject)` instead.
71- Callbacks are now called in the order they were registered.
72- `nextDates(count?: number)` now always returns an array (empty if no argument is provided). Use `nextDate()` instead for a single date.
73
74### Removed methods
75
76- removed `job()` method in favor of `new CronJob(...args)` / `CronJob.from(argsObject)`
77
78- removed `time()` method in favor of `new CronTime()`
79
80</details>
81
82## 🛠 Basic Usage
83
84```javascript
85import { CronJob } from 'cron';
86
87const job = new CronJob(
88 '* * * * * *', // cronTime
89 function () {
90 console.log('You will see this message every second');
91 }, // onTick
92 null, // onComplete
93 true, // start
94 'America/Los_Angeles' // timeZone
95);
96// job.start() is optional here because of the fourth parameter set to true.
97```
98
99```javascript
100// equivalent job using the "from" static method, providing parameters as an object
101const job = CronJob.from({
102 cronTime: '* * * * * *',
103 onTick: function () {
104 console.log('You will see this message every second');
105 },
106 start: true,
107 timeZone: 'America/Los_Angeles'
108});
109```
110
111> **Note:** In the first example above, the fourth parameter to `CronJob()` starts the job automatically. If not provided or set to falsy, you must explicitly start the job using `job.start()`.
112
113For more advanced examples, check the [examples directory](https://github.com/kelektiv/node-cron/tree/main/examples).
114
115## Cron Patterns
116
117Cron patterns are the backbone of this library. Familiarize yourself with the syntax:
118
119```
120- `*` Asterisks: Any value
121- `1-3,5` Ranges: Ranges and individual values
122- `*/2` Steps: Every two units
123```
124
125Detailed patterns and explanations are available at [crontab.org](http://crontab.org). The examples in the link have five fields, and 1 minute as the finest granularity, but our cron scheduling supports an enhanced format with six fields, allowing for second-level precision. Tools like [crontab.guru](https://crontab.guru/) can help in constructing patterns but remember to account for the seconds field.
126
127### Supported Ranges
128
129Here's a quick reference to the UNIX Cron format this library uses, plus an added second field:
130
131```
132field allowed values
133----- --------------
134second 0-59
135minute 0-59
136hour 0-23
137day of month 1-31
138month 1-12 (or names, see below)
139day of week 0-7 (0 or 7 is Sunday, or use names)
140```
141
142> Names can also be used for the 'month' and 'day of week' fields. Use the first three letters of the particular day or month (case does not matter). Ranges and lists of names are allowed.
143> Examples: "mon,wed,fri", "jan-mar".
144
145## Gotchas
146
147- Both JS `Date` and Luxon `DateTime` objects don't guarantee millisecond precision due to computation delays. This module excludes millisecond precision for standard cron syntax but allows execution date specification through JS `Date` or Luxon `DateTime` objects. However, specifying a precise future execution time, such as adding a millisecond to the current time, may not always work due to these computation delays. It's observed that delays less than 4-5 ms might lead to inconsistencies. While we could limit all date granularity to seconds, we've chosen to allow greater precision but advise users of potential issues.
148
149- Using arrow functions for `onTick` binds them to the parent's `this` context. As a result, they won't have access to the cronjob's `this` context. You can read a little more in issue [#47 (comment)](https://github.com/kelektiv/node-cron/issues/47#issuecomment-459762775).
150
151## API
152
153### Standalone Functions
154
155- `sendAt`: Indicates when a `CronTime` will execute (returns a Luxon `DateTime` object).
156
157 ```javascript
158 import * as cron from 'cron';
159
160 const dt = cron.sendAt('0 0 * * *');
161 console.log(`The job would run at: ${dt.toISO()}`);
162 ```
163
164- `timeout`: Indicates the number of milliseconds in the future at which a `CronTime` will execute (returns a number).
165
166 ```javascript
167 import * as cron from 'cron';
168
169 const timeout = cron.timeout('0 0 * * *');
170 console.log(`The job would run in ${timeout}ms`);
171 ```
172
173### CronJob Class
174
175#### Constructor
176
177`constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout)`:
178
179- `cronTime`: [REQUIRED] - The time to fire off your job. Can be cron syntax, a JS [`Date`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) object or a Luxon [`DateTime`](https://moment.github.io/luxon/api-docs/index.html#datetime) object.
180
181- `onTick`: [REQUIRED] - Function to execute at the specified time. If an `onComplete` callback was provided, `onTick` will receive it as an argument.
182
183- `onComplete`: [OPTIONAL] - Invoked when the job is halted with `job.stop()`. It might also be triggered by `onTick` post its run.
184
185- `start`: [OPTIONAL] - Determines if the job should commence before constructor exit. Default is `false`.
186
187- `timeZone`: [OPTIONAL] - Sets the execution time zone. Default is local time. Check valid formats in the [Luxon documentation](https://github.com/moment/luxon/blob/master/docs/zones.md#specifying-a-zone).
188
189- `context`: [OPTIONAL] - Execution context for the onTick method.
190
191- `runOnInit`: [OPTIONAL] - Instantly triggers the `onTick` function post initialization. Default is `false`.
192
193- `utcOffset`: [OPTIONAL] - Specifies time zone offset in minutes. Cannot co-exist with `timeZone`.
194
195- `unrefTimeout`: [OPTIONAL] - Useful for controlling event loop behavior. More details [here](https://nodejs.org/api/timers.html#timers_timeout_unref).
196
197#### Methods
198
199- `from` (static): Create a new CronJob object providing arguments as an object. See argument names and descriptions above.
200
201- `start`: Initiates the job.
202
203- `stop`: Halts the job.
204
205- `setTime`: Modifies the time for the `CronJob`. Parameter must be a `CronTime`.
206
207- `lastDate`: Provides the last execution date.
208
209- `nextDate`: Indicates the subsequent date that will activate an `onTick`.
210
211- `nextDates(count)`: Supplies an array of upcoming dates that will initiate an `onTick`.
212
213- `fireOnTick`: Allows modification of the `onTick` calling behavior.
214
215- `addCallback`: Permits addition of `onTick` callbacks.
216
217### CronTime Class
218
219#### Constructor
220
221`constructor(time, zone, utcOffset)`:
222
223- `time`: [REQUIRED] - The time to initiate your job. Accepts cron syntax or a JS [Date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) object.
224
225- `zone`: [OPTIONAL] - Equivalent to `timeZone` from `CronJob` parameters.
226
227- `utcOffset`: [OPTIONAL] - Analogous to `utcOffset` from `CronJob` parameters.
228
229## 🤝 Community
230
231Join the [Discord server](https://discord.gg/yyKns29zch)! Here you can discuss issues and get help in a more casual forum than GitHub.
232
233## 🌍 Contributing
234
235This project is looking for help! If you're interested in helping with the project, please take a look at our [contributing documentation](https://github.com/kelektiv/node-cron/blob/main/CONTRIBUTING.md).
236
237### 🐛 Submitting Bugs/Issues
238
239Please have a look at our [contributing documentation](https://github.com/kelektiv/node-cron/blob/main/CONTRIBUTING.md), it contains all the information you need to know before submitting an issue.
240
241## 🙏 Acknowledgements
242
243This is a community effort project. In the truest sense, this project started as an open source project from [cron.js](http://github.com/padolsey/cron.js) and grew into something else. Other people have contributed code, time, and oversight to the project. At this point there are too many to name here so we'll just say thanks.
244
245Special thanks to [Hiroki Horiuchi](https://github.com/horiuchi), [Lundarl Gholoi](https://github.com/winup) and [koooge](https://github.com/koooge) for their work on the [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) typings before they were imported in v2.4.0.
246
247## License
248
249MIT
250
\No newline at end of file