UNPKG

11.3 kBMarkdownView Raw
1<p align="center">
2 <img src="logo.svg" alt="Node Cron Alarm Clock Star Logo" width="100" />
3</p>
4
5# node-cron
6
7[![Version](https://badgen.net/npm/v/cron?icon=npm)](https://badgen.net/npm/v/cron)
8[![Build Status](https://badgen.net/github/status/kelektiv/node-cron?icon=github)](https://badgen.net/github/status/kelektiv/node-cron)
9[![Build Checks](https://badgen.net/github/checks/kelektiv/node-cron?icon=github)](https://badgen.net/github/checks/kelektiv/node-cron)
10[![Dependency Status](https://badgen.net/david/dep/kelektiv/node-cron)](https://badgen.net/david/dev/kelektiv/node-cron)
11[![Code Coverage](https://badgen.net/codecov/c/github/kelektiv/node-cron?icon=codecov)](https://badgen.net/codecov/c/github/kelektiv/node-cron)
12[![Known Vulnerabilities](https://snyk.io/test/github/kelektiv/node-cron/badge.svg)](https://snyk.io/test/github/kelektiv/node-cron)
13[![Minified size](https://badgen.net/bundlephobia/min/cron)](https://badgen.net/bundlephobia/min/cron)
14[![Minzipped size](https://badgen.net/bundlephobia/minzip/cron)](https://badgen.net/bundlephobia/minzip/cron)
15[![monthly downloads](https://badgen.net/npm/dm/cron?icon=npm)](https://badgen.net/npm/dm/cron)
16
17Cron is a tool that allows you to execute _something_ on a schedule. This is typically done using the cron syntax. We allow you to:
18
19- execute a function whenever your scheduled job triggers
20- execute a job external to the javascript process (like a system command) using `child_process`
21- use a Date or Luxon DateTime object instead of cron syntax as the trigger for your callback
22- use an additional slot for seconds (leaving it off will default to 0 and match the Unix behavior)
23
24## Installation
25
26```bash
27npm install cron
28```
29
30## Migrating from v2 to v3
31
32In version 3 of this library, we migrated to TypeScript, aligned our cron patterns format with the UNIX standard, and released some other breaking changes. See below for the changes you need to make when upgrading:
33
34<details>
35 <summary>Migrating from v2 to v3</summary>
36
37### Month & day-of-week indexing changes
38
39**Month indexing went from `0-11` to `1-12`. So you need to increment all numeric months by 1.**
40
41For day-of-week indexing, we only added support for `7` as Sunday, so you don't need to change anything!
42
43### CronJob changes
44
45- **constructor no longer accepts an object as its first and only params. Use `CronJob.from(argsObject)` instead.**
46- **callbacks are now called in the order they were registered.**
47
48### Removed methods
49
50- **removed `job()` method in favor of `new CronJob(...args)` / `CronJob.from(argsObject)`**
51
52- **removed `time()` method in favor of `new CronTime()`**
53
54</details>
55
56## Usage (basic cron usage)
57
58```javascript
59import { CronJob } from 'cron';
60const job = new CronJob(
61 '* * * * * *',
62 function () {
63 console.log('You will see this message every second');
64 },
65 null,
66 true,
67 'America/Los_Angeles'
68);
69// job.start() - See note below when to use this
70```
71
72Note - In the example above, the 4th parameter of `CronJob()` automatically starts the job on initialization. If this parameter is falsy or not provided, the job needs to be explicitly started using `job.start()`.
73
74There are more examples available in this repository at: [/examples](https://github.com/kelektiv/node-cron/tree/main/examples)
75
76## Available Cron patterns
77
78```
79Asterisks e.g. *
80Ranges e.g. 1-3,5
81Steps e.g. */2
82```
83
84[Read up on cron patterns here](http://crontab.org). Note the examples in the link have five fields, and 1 minute as the finest granularity, but this library has six fields, with 1 second as the finest granularity.
85
86There are tools that help when constructing your cronjobs. You might find something like https://crontab.guru/ or https://cronjob.xyz/ helpful. But, note that these don't necessarily accept the exact same syntax as this library, for instance, it doesn't accept the `seconds` field, so keep that in mind.
87
88### Cron Ranges
89
90This library follows the [UNIX Cron format](https://man7.org/linux/man-pages/man5/crontab.5.html), with an added field at the beginning for second granularity.
91
92```
93field allowed values
94----- --------------
95second 0-59
96minute 0-59
97hour 0-23
98day of month 1-31
99month 1-12 (or names, see below)
100day of week 0-7 (0 or 7 is Sunday, or use names)
101```
102
103> 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.
104> Examples: "mon,wed,fri", "jan-mar".
105
106## Gotchas
107
108- Millisecond level granularity in JS `Date` or Luxon `DateTime` objects: Because computers take time to do things, there may be some delay in execution. This should be on the order of milliseconds. This module doesn't allow MS level granularity for the regular cron syntax, but _does_ allow you to specify a real date of execution in either a javascript `Date` object or a Luxon `DateTime` object. When this happens you may find that you aren't able to execute a job that _should_ run in the future like with `new Date().setMilliseconds(new Date().getMilliseconds() + 1)`. This is due to those cycles of execution above. This wont be the same for everyone because of compute speed. When we tried it locally we saw that somewhere around the 4-5 ms mark was where we got consistent ticks using real dates, but anything less than that would result in an exception. This could be really confusing. We could restrict the granularity for all dates to seconds, but felt that it wasn't a huge problem so long as you were made aware. If this becomes more of an issue, We can revisit it.
109- Arrow Functions for `onTick`: Arrow functions get their `this` context from their parent scope. Thus, if you use them, you will not get the `this` context of the cronjob. You can read a little more in issue [GH-47](https://github.com/kelektiv/node-cron/issues/47#issuecomment-459762775)
110
111## API
112
113Parameter Based
114
115- `sendAt` - tells you when a `CronTime` will be run.
116- `timeout` - tells you when the next timeout is.
117- `CronJob`
118 - `constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout)`
119 - `cronTime` - [REQUIRED] - The time to fire off your job. This can be in the form of cron syntax or a JS [Date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) object.
120 - `onTick` - [REQUIRED] - The function to fire at the specified time. If an `onComplete` callback was provided, `onTick` will receive it as an argument. `onTick` may call `onComplete` when it has finished its work.
121 - `onComplete` - [OPTIONAL] - A function that will fire when the job is stopped with `job.stop()`, and may also be called by `onTick` at the end of each run.
122 - `start` - [OPTIONAL] - Specifies whether to start the job just before exiting the constructor. By default this is set to false. If left at default you will need to call `job.start()` in order to start the job (assuming `job` is the variable you set the cronjob to). This does not immediately fire your `onTick` function, it just gives you more control over the behavior of your jobs.
123 - `timeZone` - [OPTIONAL] - Specify the time zone for the execution. This will modify the actual time relative to your time zone. If the time zone is invalid, an error is thrown. By default (if this is omitted) the local time zone will be used. You can check the various time zones format accepted in the [Luxon documentation](https://github.com/moment/luxon/blob/master/docs/zones.md#specifying-a-zone). Note: This parameter supports minutes offsets, e.g. `UTC+5:30`. **Note**: Cannot be used together with `utcOffset`.
124 - `context` - [OPTIONAL] - The context within which to execute the onTick method. This defaults to the cronjob itself allowing you to call `this.stop()`. However, if you change this you'll have access to the functions and values within your context object.
125 - `runOnInit` - [OPTIONAL] - This will immediately fire your `onTick` function as soon as the requisite initialization has happened. This option is set to `false` by default for backwards compatibility.
126 - `utcOffset` - [OPTIONAL] - This allows you to specify the offset of your time zone rather than using the `timeZone` param. This should be an integer representing the number of minutes offset (like `120` for +2 hours or `-90` for -1.5 hours). **Note**: Cannot be used together with `timeZone`.
127 - `unrefTimeout` - [OPTIONAL] - If you have code that keeps the event loop running and want to stop the node process when that finishes regardless of the state of your cronjob, you can do so making use of this parameter. This is off by default and cron will run as if it needs to control the event loop. For more information take a look at [timers#timers_timeout_unref](https://nodejs.org/api/timers.html#timers_timeout_unref) from the NodeJS docs.
128 - `from` (static) - Create a new CronJob object providing arguments as an object. See argument names and descriptions above.
129 - `start` - Runs your job.
130 - `stop` - Stops your job.
131 - `setTime` - Stops and changes the time for the `CronJob`. Param must be a `CronTime`.
132 - `lastDate` - Tells you the last execution date.
133 - `nextDate` - Provides the next date that will trigger an `onTick`.
134 - `nextDates` - Provides an array of the next set of dates that will trigger an `onTick`.
135 - `fireOnTick` - Allows you to override the `onTick` calling behavior. This matters so only do this if you have a really good reason to do so.
136 - `addCallback` - Allows you to add `onTick` callbacks. Callbacks are run in the order they are registered.
137- `CronTime`
138 - `constructor(time, zone, utcOffset)`
139 - `time` - [REQUIRED] - The time to fire off your job. This can be in the form of cron syntax or a JS [Date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) object.
140 - `zone` - [OPTIONAL] - Same as `timeZone` from `CronJob` parameters.
141 - `utcOffset` - [OPTIONAL] - Same as `utcOffset` from `CronJob` parameters.
142
143## Community
144
145Join the [Discord server](https://discord.gg/yyKns29zch)! Here you can discuss issues and get help in a more casual forum than GitHub.
146
147## Contributing
148
149This 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).
150
151### Submitting Bugs/Issues
152
153Please 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.
154
155## Acknowledgements
156
157This 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.
158
159Special 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.
160
161## License
162
163MIT