From 0bfcd2eabfefeeb94bbf9f5bbec1e10951784b2f Mon Sep 17 00:00:00 2001 From: Harshit Raj <35199148+rharshit82@users.noreply.github.com> Date: Sat, 14 Oct 2023 19:28:56 +0530 Subject: [PATCH 1/8] basic refactoring done --- README.md | 221 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 159 insertions(+), 62 deletions(-) diff --git a/README.md b/README.md index dec43408..159b9b72 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,12 @@

- Node Cron Alarm Clock Star Logo + Node Cron Alarm Clock Star Logo

# node-cron +**node-cron** is a robust tool for running jobs (functions or commands) on schedules defined using the cron syntax. Perfect for tasks like data backups, notifications, and many more! + + [![Version](https://badgen.net/npm/v/cron?icon=npm)](https://badgen.net/npm/v/cron) [![Build Status](https://badgen.net/github/status/kelektiv/node-cron?icon=github)](https://badgen.net/github/status/kelektiv/node-cron) [![Build Checks](https://badgen.net/github/checks/kelektiv/node-cron?icon=github)](https://badgen.net/github/checks/kelektiv/node-cron) @@ -14,47 +17,84 @@ [![Minzipped size](https://badgen.net/bundlephobia/minzip/cron)](https://badgen.net/bundlephobia/minzip/cron) [![monthly downloads](https://badgen.net/npm/dm/cron?icon=npm)](https://badgen.net/npm/dm/cron) -Cron is a tool that allows you to execute _something_ on a schedule. This is typically done using the cron syntax. We allow you to: +Table of Contents +----------------- +1. [Introduction](#node-cron) + - [Logo](#node-cron) + - [Overview](#node-cron) + - [Badges](#node-cron) +2. [Features](#-features) + - [Overview](#-features) +3. [Installation](#-installation) +4. [Migration](#-migrating-from-v2-to-v3) + - [Migrating from v2 to v3](#-migrating-from-v2-to-v3) +5. [Basic Usage](#-basic-usage) + - [Code Example](#-basic-usage) + - [Note](#-basic-usage) +6. [Cron Patterns](#cron-patterns) + - [Cron Syntax Overview](#cron-patterns) + - [Supported Ranges](#supported-ranges) +7. [Gotchas](#gotchas) +8. [API](#api) + - [General Parameters](#general-parameters) + - [CronJob Class](#cronjob-class) + - [Constructor](#constructor) + - [Methods](#methods) + - [CronTime Class](#crontime-class) + - [Constructor](#constructor) +9. [Community](#-community) + - [Join the Community](#-community) +10. [Contributing](#-contributing) + - [General Contribution](#-contributing) + - [Submitting Bugs/Issues](#-submitting-bugsissues) +11. [Acknowledgements](#-acknowledgements) + - [Community Effort](#-acknowledgements) + - [Special Thanks](#-acknowledgements) +12. [License](#license) + +## 🌟 Features - execute a function whenever your scheduled job triggers - execute a job external to the javascript process (like a system command) using `child_process` - use a Date or Luxon DateTime object instead of cron syntax as the trigger for your callback - use an additional slot for seconds (leaving it off will default to 0 and match the Unix behavior) -## Installation + + +## 🚀 Installation ```bash npm install cron ``` -## Migrating from v2 to v3 +## 🔄 Migrating from v2 to v3 -In 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: +With the introduction of TypeScript in version 3 and alignment with UNIX cron patterns, a few changes have been made:
Migrating from v2 to v3 ### Month & day-of-week indexing changes -**Month indexing went from `0-11` to `1-12`. So you need to increment all numeric months by 1.** +- **Month Indexing:** Changed from `0-11` to `1-12`. Increment all numeric months by 1. -For day-of-week indexing, we only added support for `7` as Sunday, so you don't need to change anything! +- **Day-of-Week Indexing:** Support added for `7` as Sunday. -### CronJob changes +### Adjustments in `CronJob` -- **constructor no longer accepts an object as its first and only params. Use `CronJob.from(argsObject)` instead.** -- **callbacks are now called in the order they were registered.** -- **`nextDates(count?: number)` now always returns an array (empty if no argument is provided). Use `nextDate()` instead for a single date.** +- The constructor no longer accepts an object as its first and only params. Use `CronJob.from(argsObject)` instead. +- Callbacks are now called in the order they were registered. +- `nextDates(count?: number)` now always returns an array (empty if no argument is provided). Use `nextDate()` instead for a single date. ### Removed methods -- **removed `job()` method in favor of `new CronJob(...args)` / `CronJob.from(argsObject)`** +- removed `job()` method in favor of `new CronJob(...args)` / `CronJob.from(argsObject)` -- **removed `time()` method in favor of `new CronTime()`** +- removed `time()` method in favor of `new CronTime()`
-## Usage (basic cron usage) +## 🛠 Basic Usage ```javascript import { CronJob } from 'cron'; @@ -67,28 +107,31 @@ const job = new CronJob( true, 'America/Los_Angeles' ); -// job.start() - See note below when to use this +// job.start() is optional here because of the fourth parameter set to true. ``` -Note - 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()`. +> **Note:** In the 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()`. + -There are more examples available in this repository at: [/examples](https://github.com/kelektiv/node-cron/tree/main/examples) +For more advanced examples, check the [examples directory](https://github.com/kelektiv/node-cron/tree/main/examples). -## Available Cron patterns + +## Cron Patterns +Cron patterns are the backbone of this library. Familiarize yourself with the syntax: ``` -Asterisks e.g. * -Ranges e.g. 1-3,5 -Steps e.g. */2 +- `*` Asterisks: Any value +- `1-3,5` Ranges: Ranges and individual values +- `*/2` Steps: Every two units ``` -[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. +Detailed patterns and explanations are available at [crontab.org](http://crontab.org). This library provides second-level granularity unlike many other cron libraries. Tools like [crontab.guru](https://crontab.guru/) can help in constructing patterns but remember to account for the seconds field. + -There 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. +### Supported Ranges -### Cron Ranges +Here's a quick reference to the UNIX Cron format this library uses, plus an added second field: -This 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. ``` field allowed values @@ -106,55 +149,109 @@ day of week 0-7 (0 or 7 is Sunday, or use names) ## Gotchas -- 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. -- 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) +- 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. + +- 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 [GH-47](https://github.com/kelektiv/node-cron/issues/47#issuecomment-459762775) ## API -Parameter Based - -- `sendAt` - tells you when a `CronTime` will be run. -- `timeout` - tells you when the next timeout is. -- `CronJob` - - `constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout)` - - `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. - - `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. - - `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. **Note for TS users**: This should either be an arrow function, or a regular function cast to `() => void` (bug with generic type inference). - - `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. - - `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`. - - `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. - - `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. - - `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`. - - `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. - - `from` (static) - Create a new CronJob object providing arguments as an object. See argument names and descriptions above. - - `start` - Runs your job. - - `stop` - Stops your job. - - `setTime` - Stops and changes the time for the `CronJob`. Param must be a `CronTime`. - - `lastDate` - Tells you the last execution date. - - `nextDate` - Provides the next date that will trigger an `onTick`. - - `nextDates(count)` - Provides an array of the next set of dates that will trigger an `onTick`. - - `count` - [OPTIONAL] - The number of next dates to return. Defaults to 0, returning an empty array. - - `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. - - `addCallback` - Allows you to add `onTick` callbacks. Callbacks are run in the order they are registered. -- `CronTime` - - `constructor(time, zone, utcOffset)` - - `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. - - `zone` - [OPTIONAL] - Same as `timeZone` from `CronJob` parameters. - - `utcOffset` - [OPTIONAL] - Same as `utcOffset` from `CronJob` parameters. - -## Community +### General Parameters + +- `sendAt`: Indicates when a `CronTime` will execute. + ``` + Example: + let time = cron.sendAt('0 0 * * *'); + console.log(`The job will run at: ${time}`); + ``` + +- `timeout`: Indicates when the next timeout occurs. + ``` + Example: + let timeLeft = cron.timeout(); + console.log(`The next timeout is in: ${timeLeft}ms`); + ``` + +### CronJob Class + +#### Constructor + +`constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout)`: + + - `cronTime`: [REQUIRED] - The time to fire off your job. Can be cron syntax or a JS [Date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) object. + ``` + Example: + const job = new CronJob('0 0 * * *', () => { + console.log('Job executed!'); + }); + ``` + + - `onTick`: [REQUIRED] - Function to execute at the specified time. If provided, `onTick` can also receive an `onComplete` callback and might invoke it after its execution. + ``` + Example: + const onTickFunction = () => { console.log('Tick!'); }; + ``` + + - `onComplete`: [OPTIONAL] - Invoked when the job is halted with `job.stop()`. It might also be triggered by `onTick` post its run. + + - `start`: [OPTIONAL] - Determines if the job should commence before constructor exit. Default is `false`. + + - `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). + + - `context`: [OPTIONAL] - Execution context for the onTick method. + + - `runOnInit`: [OPTIONAL] - Instantly triggers the `onTick` function post initialization. Default is `false`. + + - `utcOffset`: [OPTIONAL] - Specifies time zone offset in minutes. Cannot co-exist with `timeZone`. + + - `unrefTimeout`: [OPTIONAL] - Useful for controlling event loop behavior. More details [here](https://nodejs.org/api/timers.html#timers_timeout_unref). + +#### Methods + +- `from` (static): Create a new CronJob object providing arguments as an object. + +- `start`: Initiates the job. + +- `stop`: Halts the job. + +- `setTime`: Modifies the time for the `CronJob`. Parameter must be a `CronTime`. + +- `lastDate`: Provides the last execution date. + +- `nextDate`: Indicates the subsequent date that will activate an `onTick`. + +- `nextDates(count)`: Supplies an array of upcoming dates that will initiate an `onTick`. + +- `fireOnTick`: Allows modification of the `onTick` calling behavior. + +- `addCallback`: Permits addition of `onTick` callbacks. + +### CronTime Class + +#### Constructor + +`constructor(time, zone, utcOffset)`: + + - `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. + + - `zone`: [OPTIONAL] - Equivalent to `timeZone` from `CronJob` parameters. + + - `utcOffset`: [OPTIONAL] - Analogous to `utcOffset` from `CronJob` parameters. + + + +## 🤝 Community Join the [Discord server](https://discord.gg/yyKns29zch)! Here you can discuss issues and get help in a more casual forum than GitHub. -## Contributing +## 🌍 Contributing This 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). -### Submitting Bugs/Issues +### 🐛 Submitting Bugs/Issues Please 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. -## Acknowledgements +## 🙏 Acknowledgements This 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. From aa2537c52af7245f6b2e2f5346e12c90d7631e8c Mon Sep 17 00:00:00 2001 From: Harshit Raj <35199148+rharshit82@users.noreply.github.com> Date: Sat, 14 Oct 2023 19:38:23 +0530 Subject: [PATCH 2/8] prettier formatting added --- README.md | 66 +++++++++++++++++++++++++------------------------------ 1 file changed, 30 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 159b9b72..7c0d5138 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,6 @@ **node-cron** is a robust tool for running jobs (functions or commands) on schedules defined using the cron syntax. Perfect for tasks like data backups, notifications, and many more! - [![Version](https://badgen.net/npm/v/cron?icon=npm)](https://badgen.net/npm/v/cron) [![Build Status](https://badgen.net/github/status/kelektiv/node-cron?icon=github)](https://badgen.net/github/status/kelektiv/node-cron) [![Build Checks](https://badgen.net/github/checks/kelektiv/node-cron?icon=github)](https://badgen.net/github/checks/kelektiv/node-cron) @@ -17,8 +16,8 @@ [![Minzipped size](https://badgen.net/bundlephobia/minzip/cron)](https://badgen.net/bundlephobia/minzip/cron) [![monthly downloads](https://badgen.net/npm/dm/cron?icon=npm)](https://badgen.net/npm/dm/cron) -Table of Contents ------------------ +## Table of Contents + 1. [Introduction](#node-cron) - [Logo](#node-cron) - [Overview](#node-cron) @@ -59,8 +58,6 @@ Table of Contents - use a Date or Luxon DateTime object instead of cron syntax as the trigger for your callback - use an additional slot for seconds (leaving it off will default to 0 and match the Unix behavior) - - ## 🚀 Installation ```bash @@ -112,11 +109,10 @@ const job = new CronJob( > **Note:** In the 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()`. - For more advanced examples, check the [examples directory](https://github.com/kelektiv/node-cron/tree/main/examples). - ## Cron Patterns + Cron patterns are the backbone of this library. Familiarize yourself with the syntax: ``` @@ -127,12 +123,10 @@ Cron patterns are the backbone of this library. Familiarize yourself with the sy Detailed patterns and explanations are available at [crontab.org](http://crontab.org). This library provides second-level granularity unlike many other cron libraries. Tools like [crontab.guru](https://crontab.guru/) can help in constructing patterns but remember to account for the seconds field. - ### Supported Ranges Here's a quick reference to the UNIX Cron format this library uses, plus an added second field: - ``` field allowed values ----- -------------- @@ -158,15 +152,16 @@ day of week 0-7 (0 or 7 is Sunday, or use names) ### General Parameters - `sendAt`: Indicates when a `CronTime` will execute. + ``` - Example: + Example: let time = cron.sendAt('0 0 * * *'); console.log(`The job will run at: ${time}`); ``` - `timeout`: Indicates when the next timeout occurs. ``` - Example: + Example: let timeLeft = cron.timeout(); console.log(`The next timeout is in: ${timeLeft}ms`); ``` @@ -177,40 +172,41 @@ day of week 0-7 (0 or 7 is Sunday, or use names) `constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout)`: - - `cronTime`: [REQUIRED] - The time to fire off your job. Can be cron syntax or a JS [Date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) object. - ``` - Example: - const job = new CronJob('0 0 * * *', () => { - console.log('Job executed!'); - }); - ``` +- `cronTime`: [REQUIRED] - The time to fire off your job. Can be cron syntax or a JS [Date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) object. - - `onTick`: [REQUIRED] - Function to execute at the specified time. If provided, `onTick` can also receive an `onComplete` callback and might invoke it after its execution. - ``` - Example: - const onTickFunction = () => { console.log('Tick!'); }; - ``` + ``` + Example: + const job = new CronJob('0 0 * * *', () => { + console.log('Job executed!'); + }); + ``` - - `onComplete`: [OPTIONAL] - Invoked when the job is halted with `job.stop()`. It might also be triggered by `onTick` post its run. +- `onTick`: [REQUIRED] - Function to execute at the specified time. If provided, `onTick` can also receive an `onComplete` callback and might invoke it after its execution. - - `start`: [OPTIONAL] - Determines if the job should commence before constructor exit. Default is `false`. + ``` + Example: + const onTickFunction = () => { console.log('Tick!'); }; + ``` - - `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). +- `onComplete`: [OPTIONAL] - Invoked when the job is halted with `job.stop()`. It might also be triggered by `onTick` post its run. - - `context`: [OPTIONAL] - Execution context for the onTick method. +- `start`: [OPTIONAL] - Determines if the job should commence before constructor exit. Default is `false`. - - `runOnInit`: [OPTIONAL] - Instantly triggers the `onTick` function post initialization. Default is `false`. +- `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). - - `utcOffset`: [OPTIONAL] - Specifies time zone offset in minutes. Cannot co-exist with `timeZone`. +- `context`: [OPTIONAL] - Execution context for the onTick method. - - `unrefTimeout`: [OPTIONAL] - Useful for controlling event loop behavior. More details [here](https://nodejs.org/api/timers.html#timers_timeout_unref). +- `runOnInit`: [OPTIONAL] - Instantly triggers the `onTick` function post initialization. Default is `false`. + +- `utcOffset`: [OPTIONAL] - Specifies time zone offset in minutes. Cannot co-exist with `timeZone`. + +- `unrefTimeout`: [OPTIONAL] - Useful for controlling event loop behavior. More details [here](https://nodejs.org/api/timers.html#timers_timeout_unref). #### Methods - `from` (static): Create a new CronJob object providing arguments as an object. - `start`: Initiates the job. - - `stop`: Halts the job. - `setTime`: Modifies the time for the `CronJob`. Parameter must be a `CronTime`. @@ -231,13 +227,11 @@ day of week 0-7 (0 or 7 is Sunday, or use names) `constructor(time, zone, utcOffset)`: - - `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. - - - `zone`: [OPTIONAL] - Equivalent to `timeZone` from `CronJob` parameters. - - - `utcOffset`: [OPTIONAL] - Analogous to `utcOffset` from `CronJob` parameters. +- `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. +- `zone`: [OPTIONAL] - Equivalent to `timeZone` from `CronJob` parameters. +- `utcOffset`: [OPTIONAL] - Analogous to `utcOffset` from `CronJob` parameters. ## 🤝 Community From 775f4c5eb75889a4ee5b36803d5b49a78c368133 Mon Sep 17 00:00:00 2001 From: Pierre Cavin Date: Sat, 21 Oct 2023 16:40:02 +0200 Subject: [PATCH 3/8] docs(readme): PR review suggestions --- README.md | 154 ++++++++++++++++++++++++++---------------------------- 1 file changed, 73 insertions(+), 81 deletions(-) diff --git a/README.md b/README.md index 7c0d5138..cd139545 100644 --- a/README.md +++ b/README.md @@ -1,55 +1,20 @@

- Node Cron Alarm Clock Star Logo + cron for Node.js logo +
+ cron is a robust tool for running jobs (functions or commands) on schedules defined using the cron syntax. +
+ Perfect for tasks like data backups, notifications, and many more!

-# node-cron +# cron for Node.js -**node-cron** is a robust tool for running jobs (functions or commands) on schedules defined using the cron syntax. Perfect for tasks like data backups, notifications, and many more! - -[![Version](https://badgen.net/npm/v/cron?icon=npm)](https://badgen.net/npm/v/cron) -[![Build Status](https://badgen.net/github/status/kelektiv/node-cron?icon=github)](https://badgen.net/github/status/kelektiv/node-cron) -[![Build Checks](https://badgen.net/github/checks/kelektiv/node-cron?icon=github)](https://badgen.net/github/checks/kelektiv/node-cron) -[![Dependency Status](https://badgen.net/david/dep/kelektiv/node-cron)](https://badgen.net/david/dev/kelektiv/node-cron) -[![Code Coverage](https://badgen.net/codecov/c/github/kelektiv/node-cron?icon=codecov)](https://badgen.net/codecov/c/github/kelektiv/node-cron) -[![Known Vulnerabilities](https://snyk.io/test/github/kelektiv/node-cron/badge.svg)](https://snyk.io/test/github/kelektiv/node-cron) -[![Minified size](https://badgen.net/bundlephobia/min/cron)](https://badgen.net/bundlephobia/min/cron) -[![Minzipped size](https://badgen.net/bundlephobia/minzip/cron)](https://badgen.net/bundlephobia/minzip/cron) -[![monthly downloads](https://badgen.net/npm/dm/cron?icon=npm)](https://badgen.net/npm/dm/cron) - -## Table of Contents - -1. [Introduction](#node-cron) - - [Logo](#node-cron) - - [Overview](#node-cron) - - [Badges](#node-cron) -2. [Features](#-features) - - [Overview](#-features) -3. [Installation](#-installation) -4. [Migration](#-migrating-from-v2-to-v3) - - [Migrating from v2 to v3](#-migrating-from-v2-to-v3) -5. [Basic Usage](#-basic-usage) - - [Code Example](#-basic-usage) - - [Note](#-basic-usage) -6. [Cron Patterns](#cron-patterns) - - [Cron Syntax Overview](#cron-patterns) - - [Supported Ranges](#supported-ranges) -7. [Gotchas](#gotchas) -8. [API](#api) - - [General Parameters](#general-parameters) - - [CronJob Class](#cronjob-class) - - [Constructor](#constructor) - - [Methods](#methods) - - [CronTime Class](#crontime-class) - - [Constructor](#constructor) -9. [Community](#-community) - - [Join the Community](#-community) -10. [Contributing](#-contributing) - - [General Contribution](#-contributing) - - [Submitting Bugs/Issues](#-submitting-bugsissues) -11. [Acknowledgements](#-acknowledgements) - - [Community Effort](#-acknowledgements) - - [Special Thanks](#-acknowledgements) -12. [License](#license) +[![Version](https://img.shields.io/npm/v/cron?label=version&logo=npm)](https://www.npmjs.com/package/cron) +[![Monthly Downloads](https://img.shields.io/npm/dm/cron?logo=npm)](https://www.npmjs.com/package/cron) +[![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) +[![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) +[![Coverage](https://img.shields.io/codecov/c/gh/kelektiv/node-cron?logo=codecov)](https://app.codecov.io/gh/kelektiv/node-cron) +[![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) +[![Discord](https://img.shields.io/discord/1075597081017851934?logo=discord)](https://discord.gg/yyKns29zch) ## 🌟 Features @@ -64,6 +29,28 @@ npm install cron ``` +## Table of Contents + +1. [Features](#-features) +2. [Installation](#-installation) +3. [Migrating from v2 to v3](#-migrating-from-v2-to-v3) +4. [Basic Usage](#-basic-usage) +5. [Cron Patterns](#cron-patterns) + - [Cron Syntax Overview](#cron-patterns) + - [Supported Ranges](#supported-ranges) +6. [Gotchas](#gotchas) +7. [API](#api) + - [Standalone Functions](#standalone-functions) + - [CronJob Class](#cronjob-class) + - [CronTime Class](#crontime-class) +8. [Community](#-community) + - [Join the Community](#-community) +9. [Contributing](#-contributing) + - [General Contribution](#-contributing) + - [Submitting Bugs/Issues](#-submitting-bugsissues) +10. [Acknowledgements](#-acknowledgements) +11. [License](#license) + ## 🔄 Migrating from v2 to v3 With the introduction of TypeScript in version 3 and alignment with UNIX cron patterns, a few changes have been made: @@ -95,19 +82,32 @@ With the introduction of TypeScript in version 3 and alignment with UNIX cron pa ```javascript import { CronJob } from 'cron'; + const job = new CronJob( - '* * * * * *', + '* * * * * *', // cronTime function () { console.log('You will see this message every second'); - }, - null, - true, - 'America/Los_Angeles' + }, // onTick + null, // onComplete + true, // start + 'America/Los_Angeles' // timeZone ); // job.start() is optional here because of the fourth parameter set to true. ``` -> **Note:** In the 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()`. +```javascript +// equivalent job using the "from" static method, providing parameters as an object +const job = CronJob.from({ + cronTime: '* * * * * *', + onTick: function () { + console.log('You will see this message every second'); + }, + start: true, + timeZone: 'America/Los_Angeles' +}); +``` + +> **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()`. For more advanced examples, check the [examples directory](https://github.com/kelektiv/node-cron/tree/main/examples). @@ -145,25 +145,28 @@ day of week 0-7 (0 or 7 is Sunday, or use names) - 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. -- 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 [GH-47](https://github.com/kelektiv/node-cron/issues/47#issuecomment-459762775) +- 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). ## API -### General Parameters +### Standalone Functions -- `sendAt`: Indicates when a `CronTime` will execute. +- `sendAt`: Indicates when a `CronTime` will execute (returns a Luxon `DateTime` object). - ``` - Example: - let time = cron.sendAt('0 0 * * *'); - console.log(`The job will run at: ${time}`); - ``` + ```javascript + import * as cron from 'cron'; -- `timeout`: Indicates when the next timeout occurs. + const dt = cron.sendAt('0 0 * * *'); + console.log(`The job would run at: ${dt.toISO()}`); ``` - Example: - let timeLeft = cron.timeout(); - console.log(`The next timeout is in: ${timeLeft}ms`); + +- `timeout`: Indicates the number of milliseconds in the future at which a `CronTime` will execute (returns a number). + + ```javascript + import * as cron from 'cron'; + + const timeout = cron.timeout('0 0 * * *'); + console.log(`The job would run in ${timeout}ms`); ``` ### CronJob Class @@ -172,21 +175,9 @@ day of week 0-7 (0 or 7 is Sunday, or use names) `constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout)`: -- `cronTime`: [REQUIRED] - The time to fire off your job. Can be cron syntax or a JS [Date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) object. - - ``` - Example: - const job = new CronJob('0 0 * * *', () => { - console.log('Job executed!'); - }); - ``` +- `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. -- `onTick`: [REQUIRED] - Function to execute at the specified time. If provided, `onTick` can also receive an `onComplete` callback and might invoke it after its execution. - - ``` - Example: - const onTickFunction = () => { console.log('Tick!'); }; - ``` +- `onTick`: [REQUIRED] - Function to execute at the specified time. If an `onComplete` callback was provided, `onTick` will receive it as an argument. - `onComplete`: [OPTIONAL] - Invoked when the job is halted with `job.stop()`. It might also be triggered by `onTick` post its run. @@ -204,9 +195,10 @@ day of week 0-7 (0 or 7 is Sunday, or use names) #### Methods -- `from` (static): Create a new CronJob object providing arguments as an object. +- `from` (static): Create a new CronJob object providing arguments as an object. See argument names and descriptions above. - `start`: Initiates the job. + - `stop`: Halts the job. - `setTime`: Modifies the time for the `CronJob`. Parameter must be a `CronTime`. From 3647be437505dabd0f73dd226eb1cba59573adc9 Mon Sep 17 00:00:00 2001 From: Harshit Raj <35199148+rharshit82@users.noreply.github.com> Date: Sat, 21 Oct 2023 20:51:24 +0530 Subject: [PATCH 4/8] docs(readme): minor capitalization added docs(readme): minor capitalization added --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cd139545..1c50d0f6 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Perfect for tasks like data backups, notifications, and many more!

-# cron for Node.js +# Cron for Node.js [![Version](https://img.shields.io/npm/v/cron?label=version&logo=npm)](https://www.npmjs.com/package/cron) [![Monthly Downloads](https://img.shields.io/npm/dm/cron?logo=npm)](https://www.npmjs.com/package/cron) From 1262fd9e7d87740214263d8d683a52a38e2d5138 Mon Sep 17 00:00:00 2001 From: Harshit Raj <35199148+rharshit82@users.noreply.github.com> Date: Wed, 25 Oct 2023 23:51:08 +0530 Subject: [PATCH 5/8] review change 1 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1c50d0f6..bba7acd4 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ With the introduction of TypeScript in version 3 and alignment with UNIX cron pa ### Month & day-of-week indexing changes -- **Month Indexing:** Changed from `0-11` to `1-12`. Increment all numeric months by 1. +- **Month Indexing:** Changed from `0-11` to `1-12`. So you need to increment all numeric months by 1. - **Day-of-Week Indexing:** Support added for `7` as Sunday. From f99fddc1be97eee75d3b7b74944b13e5c2910dce Mon Sep 17 00:00:00 2001 From: Harshit Raj <35199148+rharshit82@users.noreply.github.com> Date: Wed, 25 Oct 2023 23:55:39 +0530 Subject: [PATCH 6/8] review change 2 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bba7acd4..dc637884 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ Cron patterns are the backbone of this library. Familiarize yourself with the sy - `*/2` Steps: Every two units ``` -Detailed patterns and explanations are available at [crontab.org](http://crontab.org). This library provides second-level granularity unlike many other cron libraries. Tools like [crontab.guru](https://crontab.guru/) can help in constructing patterns but remember to account for the seconds field. +Detailed 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. ### Supported Ranges From 2913c5ca50c364fbade7673795fd200152de62ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Brandon=20der=20Bl=C3=A4tter?= Date: Wed, 25 Oct 2023 16:53:46 -0700 Subject: [PATCH 7/8] add Renovate badge to README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index dc637884..f0b1a895 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ [![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) [![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) [![Coverage](https://img.shields.io/codecov/c/gh/kelektiv/node-cron?logo=codecov)](https://app.codecov.io/gh/kelektiv/node-cron) +[![Renovate](https://img.shields.io/badge/renovate-enabled-green)](https://img.shields.io/badge/renovate-enabled-green) [![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) [![Discord](https://img.shields.io/discord/1075597081017851934?logo=discord)](https://discord.gg/yyKns29zch) From 0c0d5d3aa762f5c413f9ca8c1854f2121e48e5cd Mon Sep 17 00:00:00 2001 From: Pierre Cavin Date: Thu, 26 Oct 2023 14:51:18 +0200 Subject: [PATCH 8/8] docs(readme): fix renovate badge color & add link to dependency dashboard --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f0b1a895..35bebef5 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ [![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) [![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) [![Coverage](https://img.shields.io/codecov/c/gh/kelektiv/node-cron?logo=codecov)](https://app.codecov.io/gh/kelektiv/node-cron) -[![Renovate](https://img.shields.io/badge/renovate-enabled-green)](https://img.shields.io/badge/renovate-enabled-green) +[![Renovate](https://img.shields.io/badge/renovate-enabled-dark_green)](https://github.com/kelektiv/node-cron/issues/718) [![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) [![Discord](https://img.shields.io/discord/1075597081017851934?logo=discord)](https://discord.gg/yyKns29zch)