Socket
Socket
Sign inDemoInstall

cron

Package Overview
Dependencies
2
Maintainers
3
Versions
66
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 3.1.4 to 3.1.5

26

CHANGELOG.md

@@ -0,1 +1,27 @@

## [3.1.5](https://github.com/kelektiv/node-cron/compare/v3.1.4...v3.1.5) (2023-10-26)
### πŸ› Bug Fixes
* detect multiple zeros as an invalid step ([#743](https://github.com/kelektiv/node-cron/issues/743)) [skip ci] ([b0bf677](https://github.com/kelektiv/node-cron/commit/b0bf677ee7b7c322dbe2c9feb13257787edc4fb8))
* re-add runOnce property to CronJob ([#751](https://github.com/kelektiv/node-cron/issues/751)) ([a61d8c9](https://github.com/kelektiv/node-cron/commit/a61d8c95057b6055a2fe0f18896a098f5d0266e0))
### πŸ“š Documentation
* **readme:** API documentation overhaul ([#716](https://github.com/kelektiv/node-cron/issues/716)) [skip ci] ([23fb0a3](https://github.com/kelektiv/node-cron/commit/23fb0a383fc5dea2f677d69638a1c34ec49b6425))
### βš™οΈ Continuous Integrations
* **action:** update actions/setup-node action to v4 ([#749](https://github.com/kelektiv/node-cron/issues/749)) ([ef850f3](https://github.com/kelektiv/node-cron/commit/ef850f32f0b429825e2bea59fedbf53fa0053894))
### ♻️ Chores
* **deps:** update dependency [@commitlint](https://github.com/commitlint)/cli to v18 ([#747](https://github.com/kelektiv/node-cron/issues/747)) ([5ff1cf8](https://github.com/kelektiv/node-cron/commit/5ff1cf826b376b1c3a03003b771ce8ca96edfaf5))
* **deps:** update dependency sinon to v17 ([#748](https://github.com/kelektiv/node-cron/issues/748)) ([9d61ff9](https://github.com/kelektiv/node-cron/commit/9d61ff976371ebf93bcfedf8386ba4fe426dcac5))
* **deps:** update linters ([7bdc726](https://github.com/kelektiv/node-cron/commit/7bdc726e8960d89b489a648eb5918090c7ee01c9))
* improve ossf scorecard's score ([#715](https://github.com/kelektiv/node-cron/issues/715)) [skip ci] ([1284df4](https://github.com/kelektiv/node-cron/commit/1284df476ec7bbcbc6493ab38af4cb4d3542580b))
## [3.1.4](https://github.com/kelektiv/node-cron/compare/v3.1.3...v3.1.4) (2023-10-24)

@@ -2,0 +28,0 @@

4

dist/errors.d.ts

@@ -1,3 +0,5 @@

export declare class ExclusiveParametersError extends Error {
export declare class CronError extends Error {
}
export declare class ExclusiveParametersError extends CronError {
constructor(param1: string, param2: string);
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExclusiveParametersError = void 0;
class ExclusiveParametersError extends Error {
exports.ExclusiveParametersError = exports.CronError = void 0;
class CronError extends Error {
}
exports.CronError = CronError;
class ExclusiveParametersError extends CronError {
constructor(param1, param2) {

@@ -6,0 +9,0 @@ super(`You can't specify both ${param1} and ${param2}`);

@@ -10,2 +10,3 @@ import { CronTime } from './time';

onComplete?: WithOnComplete<OC> extends true ? CronOnCompleteCallback : undefined;
get runOnce(): boolean;
private _timeout?;

@@ -12,0 +13,0 @@ private _callbacks;

@@ -8,2 +8,5 @@ "use strict";

class CronJob {
get runOnce() {
return this.cronTime.realDate;
}
constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout) {

@@ -77,3 +80,3 @@ this.running = false;

if (!(time instanceof time_1.CronTime)) {
throw new Error('time must be an instance of CronTime.');
throw new errors_1.CronError('time must be an instance of CronTime.');
}

@@ -135,3 +138,3 @@ const wasRunning = this.running;

this.running = false;
if (!this.cronTime.realDate) {
if (!this.runOnce) {
this.start();

@@ -138,0 +141,0 @@ }

@@ -23,3 +23,3 @@ "use strict";

if (!dt.isValid) {
throw new Error('Invalid timezone.');
throw new errors_1.CronError('Invalid timezone.');
}

@@ -89,3 +89,3 @@ this.timeZone = timeZone;

if (!date.isValid) {
throw new Error('ERROR: You specified an invalid UTC offset.');
throw new errors_1.CronError('ERROR: You specified an invalid UTC offset.');
}

@@ -95,3 +95,3 @@ }

if (luxon_1.DateTime.local() > date) {
throw new Error('WARNING: Date in past. Will never be fired.');
throw new errors_1.CronError('WARNING: Date in past. Will never be fired.');
}

@@ -139,3 +139,3 @@ return date;

if (!date.isValid) {
throw new Error('ERROR: You specified an invalid date.');
throw new errors_1.CronError('ERROR: You specified an invalid date.');
}

@@ -146,3 +146,3 @@ const maxMatch = luxon_1.DateTime.now().plus({ years: 8 });

if (date > maxMatch) {
throw new Error(`Something went wrong. No execution date was found in the next 8 years.
throw new errors_1.CronError(`Something went wrong. No execution date was found in the next 8 years.
Please provide the following string if you would like to help debug:

@@ -257,3 +257,3 @@ Time Zone: ${(_a = timeZone === null || timeZone === void 0 ? void 0 : timeZone.toString()) !== null && _a !== void 0 ? _a : '""'} - Cron String: ${this.source.toString()} - UTC offset: ${date.offset} - current Date: ${luxon_1.DateTime.local().toString()}`);

if (++iteration > iterationLimit) {
throw new Error(`ERROR: This DST checking related function assumes the input DateTime (${(_a = date.toISO()) !== null && _a !== void 0 ? _a : date.toMillis()}) is within 24 hours of a DST jump.`);
throw new errors_1.CronError(`ERROR: This DST checking related function assumes the input DateTime (${(_a = date.toISO()) !== null && _a !== void 0 ? _a : date.toMillis()}) is within 24 hours of a DST jump.`);
}

@@ -309,3 +309,3 @@ expectedMinute = maybeJumpingPoint.minute - 1;

if (startHour >= endHour) {
throw new Error(`ERROR: This DST checking related function assumes the forward jump starting hour (${startHour}) is less than the end hour (${endHour})`);
throw new errors_1.CronError(`ERROR: This DST checking related function assumes the forward jump starting hour (${startHour}) is less than the end hour (${endHour})`);
}

@@ -375,10 +375,10 @@ const firstHourMinuteRange = Array.from({ length: 60 - startMinute }, (_, k) => startMinute + k);

}
throw new Error(`Unknown alias: ${alias}`);
throw new errors_1.CronError(`Unknown alias: ${alias}`);
});
const units = source.trim().split(/\s+/);
if (units.length < constants_1.TIME_UNITS_LEN - 1) {
throw new Error('Too few fields');
throw new errors_1.CronError('Too few fields');
}
if (units.length > constants_1.TIME_UNITS_LEN) {
throw new Error('Too many fields');
throw new errors_1.CronError('Too many fields');
}

@@ -402,3 +402,3 @@ const unitsLen = units.length;

if (wildcardIndex !== -1 && wildcardIndex !== 0) {
throw new Error(`Field (${field}) has an invalid wildcard expression`);
throw new errors_1.CronError(`Field (${field}) has an invalid wildcard expression`);
}

@@ -415,8 +415,8 @@ });

const wasStepDefined = mStep !== undefined;
if (mStep === '0') {
throw new Error(`Field (${unit}) has a step of zero`);
const step = parseInt(mStep !== null && mStep !== void 0 ? mStep : '1', 10);
if (step === 0) {
throw new errors_1.CronError(`Field (${unit}) has a step of zero`);
}
const step = parseInt(mStep !== null && mStep !== void 0 ? mStep : '1', 10);
if (upper !== undefined && lower > upper) {
throw new Error(`Field (${unit}) has an invalid range`);
throw new errors_1.CronError(`Field (${unit}) has an invalid range`);
}

@@ -427,3 +427,3 @@ const isOutOfRange = lower < low ||

if (isOutOfRange) {
throw new Error(`Field value (${value}) is out of range`);
throw new errors_1.CronError(`Field value (${value}) is out of range`);
}

@@ -449,3 +449,3 @@ lower = Math.min(Math.max(low, ~~Math.abs(lower)), high);

else {
throw new Error(`Field (${unit}) cannot be parsed`);
throw new errors_1.CronError(`Field (${unit}) cannot be parsed`);
}

@@ -452,0 +452,0 @@ }

{
"name": "cron",
"description": "Cron jobs for your node",
"version": "3.1.4",
"version": "3.1.5",
"author": "Nick Campbell <nicholas.j.campbell@gmail.com> (https://github.com/ncb000gt)",

@@ -22,2 +22,3 @@ "bugs": {

"test:watch": "jest --watch --coverage",
"test:fuzz": "jest --testMatch='**/*.fuzz.ts' --coverage=false --testTimeout=120000",
"prepare": "husky install",

@@ -31,3 +32,4 @@ "release": "semantic-release"

"devDependencies": {
"@commitlint/cli": "17.8.0",
"@commitlint/cli": "18.0.0",
"@fast-check/jest": "1.7.3",
"@insurgentlab/commitlint-config": "18.1.3",

@@ -46,5 +48,5 @@ "@insurgentlab/conventional-changelog-preset": "7.0.0",

"chai": "4.3.10",
"eslint": "8.51.0",
"eslint": "8.52.0",
"eslint-config-prettier": "9.0.0",
"eslint-plugin-jest": "27.4.2",
"eslint-plugin-jest": "27.4.3",
"eslint-plugin-prettier": "5.0.1",

@@ -55,3 +57,3 @@ "husky": "8.0.3",

"semantic-release": "22.0.5",
"sinon": "16.1.3",
"sinon": "17.0.0",
"ts-jest": "29.1.1",

@@ -58,0 +60,0 @@ "typescript": "5.2.2"

<p align="center">
<img src="logo.svg" alt="Node Cron Alarm Clock Star Logo" width="100" />
<img src="logo.svg" alt="cron for Node.js logo" height="150">
<br />
<b>cron</b> is a robust tool for running jobs (functions or commands) on schedules defined using the cron syntax.
<br />
Perfect for tasks like data backups, notifications, and many more!
</p>
# node-cron
# Cron for Node.js
[![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)
[![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)
[![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)
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:
## 🌟 Features

@@ -24,3 +27,3 @@ - execute a function whenever your scheduled job triggers

## Installation
## πŸš€ Installation

@@ -31,6 +34,28 @@ ```bash

## Migrating from v2 to v3
## Table of Contents
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:
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:
<details>

@@ -41,56 +66,69 @@ <summary>Migrating from v2 to v3</summary>

**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`. So you need to 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()`
</details>
## Usage (basic cron usage)
## πŸ›  Basic Usage
```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() - 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()`.
```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'
});
```
There are more examples available in this repository at: [/examples](https://github.com/kelektiv/node-cron/tree/main/examples)
> **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()`.
## Available Cron patterns
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:
```
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). 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.
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.
```

@@ -112,51 +150,97 @@ field allowed values

- 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 [#47 (comment)](https://github.com/kelektiv/node-cron/issues/47#issuecomment-459762775).
## API
Parameter Based
### Standalone Functions
- `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.
- `sendAt`: Indicates when a `CronTime` will execute (returns a Luxon `DateTime` object).
## Community
```javascript
import * as cron from 'cron';
const dt = cron.sendAt('0 0 * * *');
console.log(`The job would run at: ${dt.toISO()}`);
```
- `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
#### Constructor
`constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout)`:
- `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 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.
- `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. 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`.
- `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

@@ -163,0 +247,0 @@ 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.

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚑️ by Socket Inc