Gathering detailed insights and metrics for cron-schedule
Gathering detailed insights and metrics for cron-schedule
Gathering detailed insights and metrics for cron-schedule
Gathering detailed insights and metrics for cron-schedule
A zero-dependency cron parser and scheduler for Node.js, Deno and the browser.
npm install cron-schedule
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
178 Stars
427 Commits
15 Forks
2 Watching
8 Branches
10 Contributors
Updated on 20 Nov 2024
TypeScript (100%)
Cumulative downloads
Total Downloads
Last day
5%
11,921
Compared to previous day
Last week
2.1%
64,642
Compared to previous week
Last month
7.8%
264,365
Compared to previous month
Last year
-46.5%
4,193,778
Compared to previous year
6
A zero-dependency cron parser and scheduler for Node.js, Deno and the browser. Published on NPM and JSR
Via npm:
$ npm install cron-schedule
Via yarn:
$ yarn add cron-schedule
Via pnpm:
$ pnpm add cron-schedule
We test our code against the following Node.js releases (18.20
, 20.12
).
Other versions of node.js may also work, but this is not tested.
1import { parseCronExpression } from 'cron-schedule' 2const cron = parseCronExpression('*/5 * * * *') 3console.log(cron.getNextDate(new Date(2020, 10, 20, 18, 32))) 4// 2020-11-20T17:35:00.000Z
1<script type="module"> 2 import { parseCronExpression } from 'https://cdn.skypack.dev/cron-schedule@:version' 3 const cron = parseCronExpression('*/5 * * * *') 4 console.log(cron.getNextDate(new Date(2020, 10, 20, 18, 32))) 5 // 2020-11-20T17:35:00.000Z 6</script>
The examples above uses Skypack.
1import { parseCronExpression } from 'npm:cron-schedule@:version' 2const cron = parseCronExpression('*/5 * * * *') 3console.log(cron.getNextDate(new Date(2020, 10, 20, 18, 32))) 4// 2020-11-20T17:35:00.000Z
Alternatively you can use deno add @p4sca1/cron-schedule
and import from @p4sca1/cron-schedule
, or import from jsr:@p4sca1/cron-schedule
without an install step.
The deno import and Skypack CDN urls contain a :version
placeholder. Replace :version
with the desired version. Semver ranges are supported. To always use the latest 4.x
version use ^4.0.0
.
See https://www.npmjs.com/package/cron-schedule for a list of available versions.
1// Import method to parse a cron expression. 2import { parseCronExpression } from 'cron-schedule' 3 4// Parse a cron expression to return a Cron instance. 5const cron = parseCronExpression('*/5 * * * *') 6 7// Get the next date starting from the given start date or now. 8cron.getNextDate(startDate?: Date): Date 9 10// Get the specified amount of future dates starting from the given start date or now. 11cron.getNextDates(amount: number, startDate?: Date): Date[] 12 13// Get an ES6 compatible iterator which iterates over the next dates starting from startDate or now. 14// The iterator runs until the optional endDate is reached or forever. 15// The advantage of an iterator is that you can get more further dates on demand by using iterator.next(). 16cron.getNextDatesIterator(startDate: Date = new Date(), endDate?: Date): Generator<Date, undefined, undefined> 17 18// Get the previou date starting from the given start date or now. 19cron.getPrevDate(startDate: Date = new Date()): Date 20 21// Get the specified amount of previous dates starting from the given start date or now. 22cron.getPrevDates(amount: number, startDate?: Date): Date[] 23 24// Get an ES6 compatible iterator which iterates over the previous dates starting from startDate or now. 25// The iterator runs until the optional endDate is reached or forever. 26// The advantage of an iterator is that you can get more previous dates on demand by using iterator.next(). 27cron.getPrevDatesIterator(startDate: Date = new Date(), endDate?: Date): Generator<Date, undefined, undefined> 28 29// Check whether there is a cron date at the given date. 30cron.matchDate(date: Date): boolean
You can schedule tasks to be executed based on a cron expression. cron-schedule comes with 2 different schedulers.
If you use TypeScript, make sure you set compilerOptions.moduleResolution
to node16
or nodenext
.
The timer based cron scheduler creates one timer for every scheduled cron. When the node timeout limit of ~24 days would be exceeded, it uses multiple consecutive timeouts.
1// Import the scheduler. 2import { TimerBasedCronScheduler as scheduler } from 'cron-schedule/schedulers/timer-based.js' 3 4// Create a timeout, which fill fire the task on the next cron date. 5// An optional errorHandler can be provided, which is called when the task throws an error or returns a promise that gets rejected. 6// Returns a handle which can be used to clear the timeout using clearTimeoutOrInterval. 7scheduler.setTimeout(cron: Cron, task: () => unknown, opts?: { errorHandler?: (err: Error) => unknown }): ITimerHandle 8 9// Create an interval, which will fire the given task on every future cron date. 10// This uses consecutive calls to scheduler.setTimeout under the hood. 11// An optional errorHandler can be provided, which is called when the task throws an error or returns a promise that gets rejected. 12// The task remains scheduled when an error occurs. 13// Returns a handle which can be used to clear the timeout using clearTimeoutOrInterval. 14scheduler.setInterval(cron: Cron, task: () => unknown, opts?: { errorHandler?: (err: Error) => unknown }): ITimerHandle 15 16// Clear a timeout or interval, making sure that the task will no longer execute. 17scheduler.clearTimeoutOrInterval(handle: ITimerHandle): void
Pros:
Cons:
The interval based scheduler checks for due task in a fixed interval. So there is only one interval for all tasks assigned to a scheduler. You can have multiple instances of an interval based scheduler.
1// Import the scheduler. 2import { IntervalBasedCronScheduler } from 'cron-schedule/schedulers/interval-based.js' 3 4// Instantiate a new instance of the scheduler with the given interval. In this example, the scheduler would check every 60 seconds. 5const scheduler = new IntervalBasedCronScheduler(60 * 1000) 6 7// Register a new task that will be executed on every future cron date, or only on the next cron date if isOneTimeTask is true. 8// An optional errorHandler can be provided, which is called when the task throws an error or returns a promise that gets rejected. 9// The task remains scheduled when an error occurs (if not a one time task). Tasks are at max executed only once per interval. 10// Returns an id to be used with unregisterTask. 11scheduler.registerTask(cron: Cron, task: () => unknown, opts?: { isOneTimeTask?: boolean, errorHandler?: (err: Error) => unknown }): number 12 13// Unregister a task causing it to no longer be executed. 14scheduler.unregisterTask(id: number): void 15 16// You can stop the scheduler, which clears the interval. 17scheduler.stop() 18 19// You can start the scheduler after stopping it again. A newly created scheduler is started by default. 20// Tasks that were due while the scheduler was stopped will be executed on the next interval tick (but only a single time). 21scheduler.start()
Pros:
Cons:
For most people, the timer based scheduler should be a good option. However, setTimeout can be unreliable for long delays. When you have problems with long timeouts / intervals being skipped, or have performance problems because of many scheduled tasks, you should consider the interval based scheduler.
cron_schedule uses the linux cron syntax as described here with the addition that you can optionally specify seconds by prepending the minute field with another field.
┌───────────── second (0 - 59, optional)
│ ┌───────────── minute (0 - 59)
│ │ ┌───────────── hour (0 - 23)
│ │ │ ┌───────────── day of month (1 - 31)
│ │ │ │ ┌───────────── month (1 - 12)
│ │ │ │ │ ┌───────────── weekday (0 - 7)
* * * * * *
All linux cron features are supported, including
For simple timing tasks like every x seconds, you should consider using setInterval
which is more suitable for simple timing tasks, as it does not have the calculation overhead.
Looking for a way to validate cron expressions in your backend (node.js) or in the browser with support for multiple presets? Check out cron-validate!
Use the npm-cron-schedule
preset to validate that cron expressions are supported by cron-schedule.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
SAST tool detected but not run on all commits
Details
Reason
5 existing vulnerabilities detected
Details
Reason
2 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 2
Reason
Found 3/25 approved changesets -- score normalized to 1
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
Project has not signed or included provenance with any releases.
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More