{"id":15486018,"url":"https://github.com/p4sca1/cron-schedule","last_synced_at":"2025-05-15T08:11:10.239Z","repository":{"id":37282555,"uuid":"300029363","full_name":"P4sca1/cron-schedule","owner":"P4sca1","description":"A zero-dependency cron parser and scheduler for Node.js, Deno and the browser.","archived":false,"fork":false,"pushed_at":"2025-05-08T20:13:20.000Z","size":471364,"stargazers_count":188,"open_issues_count":19,"forks_count":17,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-10T15:46:29.763Z","etag":null,"topics":["cron","cron-expression","cron-schedule","deno","hacktoberfest","interval","iterator","javascript","job","nodejs","parser","schedule","schedule-tasks","timer","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/P4sca1.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2020-09-30T19:04:49.000Z","updated_at":"2025-03-08T15:22:41.000Z","dependencies_parsed_at":"2024-01-15T20:26:45.753Z","dependency_job_id":"d6610851-32d1-4b5b-89d4-d47631b1b4d6","html_url":"https://github.com/P4sca1/cron-schedule","commit_stats":{"total_commits":418,"total_committers":12,"mean_commits":"34.833333333333336","dds":0.6267942583732058,"last_synced_commit":"d9882da63728cc9d2cd7f004c19636787caf21a9"},"previous_names":[],"tags_count":28,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/P4sca1%2Fcron-schedule","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/P4sca1%2Fcron-schedule/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/P4sca1%2Fcron-schedule/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/P4sca1%2Fcron-schedule/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/P4sca1","download_url":"https://codeload.github.com/P4sca1/cron-schedule/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254301432,"owners_count":22047904,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cron","cron-expression","cron-schedule","deno","hacktoberfest","interval","iterator","javascript","job","nodejs","parser","schedule","schedule-tasks","timer","typescript"],"created_at":"2024-10-02T06:05:46.035Z","updated_at":"2025-05-15T08:11:10.211Z","avatar_url":"https://github.com/P4sca1.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# cron-schedule ![CircleCI](https://circleci.com/gh/P4sca1/cron-schedule.svg?style=svg)\n\nA zero-dependency cron parser and scheduler for Node.js, Deno and the browser. Published on [NPM](https://www.npmjs.com) and [JSR](https://jsr.io)\n\n![ts](https://flat.badgen.net/badge/-/TypeScript?icon=typescript\u0026label\u0026labelColor=blue\u0026color=555555)\n[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=flat-square)](https://github.com/semantic-release/semantic-release)\n![](https://img.shields.io/npm/dw/cron-schedule?style=flat-square)\n\n## Features\n\n- Parse cron expressions.\n- Get next or previous schedules from a specific starting date.\n- Check if a date matches a cron expression.\n- Schedule a function call based on a cron expression.\n- Supports Node.js, Deno and the browser (ESM only)\n- [Lightweight](https://bundlephobia.com/result?p=cron-schedule@latest) and tree-shakeable.\n\n## Installation and usage\n\n### Node.js\n\nVia npm:\n\n`$ npm install cron-schedule`\n\nVia yarn:\n\n`$ yarn add cron-schedule`\n\nVia pnpm:\n\n`$ pnpm add cron-schedule`\n\n**We test our code against the following Node.js releases (`18.20`, `20.12`).**\nOther versions of node.js may also work, but this is not tested.\n\n##### Usage\n\n```ts\nimport { parseCronExpression } from 'cron-schedule'\nconst cron = parseCronExpression('*/5 * * * *')\nconsole.log(cron.getNextDate(new Date(2020, 10, 20, 18, 32)))\n// 2020-11-20T17:35:00.000Z\n```\n\n### Browser via CDN\n\n```html\n\u003cscript type=\"module\"\u003e\n  import { parseCronExpression } from 'https://cdn.skypack.dev/cron-schedule@:version'\n  const cron = parseCronExpression('*/5 * * * *')\n  console.log(cron.getNextDate(new Date(2020, 10, 20, 18, 32)))\n  // 2020-11-20T17:35:00.000Z\n\u003c/script\u003e\n```\n\nThe examples above uses [Skypack](https://www.skypack.dev).\n\n### Deno\n\n```ts\nimport { parseCronExpression } from 'npm:cron-schedule@:version'\nconst cron = parseCronExpression('*/5 * * * *')\nconsole.log(cron.getNextDate(new Date(2020, 10, 20, 18, 32)))\n// 2020-11-20T17:35:00.000Z\n```\n\nAlternatively 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.\n\n### Note on :version placeholder\n\nThe 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`.\nSee https://www.npmjs.com/package/cron-schedule for a list of available versions.\n\n## Work with cron expressions\n\n```ts\n// Import method to parse a cron expression.\nimport { parseCronExpression } from 'cron-schedule'\n\n// Parse a cron expression to return a Cron instance.\nconst cron = parseCronExpression('*/5 * * * *')\n\n// Get the next date starting from the given start date or now.\ncron.getNextDate(startDate?: Date): Date\n\n// Get the specified amount of future dates starting from the given start date or now.\ncron.getNextDates(amount: number, startDate?: Date): Date[]\n\n// Get an ES6 compatible iterator which iterates over the next dates starting from startDate or now.\n// The iterator runs until the optional endDate is reached or forever.\n// The advantage of an iterator is that you can get more further dates on demand by using iterator.next().\ncron.getNextDatesIterator(startDate: Date = new Date(), endDate?: Date): Generator\u003cDate, undefined, undefined\u003e\n\n// Get the previou date starting from the given start date or now.\ncron.getPrevDate(startDate: Date = new Date()): Date\n\n// Get the specified amount of previous dates starting from the given start date or now.\ncron.getPrevDates(amount: number, startDate?: Date): Date[]\n\n// Get an ES6 compatible iterator which iterates over the previous dates starting from startDate or now.\n// The iterator runs until the optional endDate is reached or forever.\n// The advantage of an iterator is that you can get more previous dates on demand by using iterator.next().\ncron.getPrevDatesIterator(startDate: Date = new Date(), endDate?: Date): Generator\u003cDate, undefined, undefined\u003e\n\n// Check whether there is a cron date at the given date.\ncron.matchDate(date: Date): boolean\n```\n\n## Schedule tasks based on cron expressions\n\nYou can schedule tasks to be executed based on a cron expression. _cron-schedule_ comes with 2 different schedulers.\n\nIf you use TypeScript, make sure you set `compilerOptions.moduleResolution` to `node16` or `nodenext`.\n\n### 1. Timer based scheduler\n\nThe timer based cron scheduler creates one timer for every scheduled cron.\nWhen the node timeout limit of ~24 days would be exceeded, it uses multiple consecutive timeouts.\n\n```ts\n// Import the scheduler.\nimport { TimerBasedCronScheduler as scheduler } from 'cron-schedule/schedulers/timer-based.js'\n\n// Create a timeout, which fill fire the task on the next cron date.\n// An optional errorHandler can be provided, which is called when the task throws an error or returns a promise that gets rejected.\n// Returns a handle which can be used to clear the timeout using clearTimeoutOrInterval.\nscheduler.setTimeout(cron: Cron, task: () =\u003e unknown, opts?: { errorHandler?: (err: Error) =\u003e unknown }): ITimerHandle\n\n// Create an interval, which will fire the given task on every future cron date.\n// This uses consecutive calls to scheduler.setTimeout under the hood.\n// An optional errorHandler can be provided, which is called when the task throws an error or returns a promise that gets rejected.\n// The task remains scheduled when an error occurs.\n// Returns a handle which can be used to clear the timeout using clearTimeoutOrInterval.\nscheduler.setInterval(cron: Cron, task: () =\u003e unknown, opts?: { errorHandler?: (err: Error) =\u003e unknown }): ITimerHandle\n\n// Clear a timeout or interval, making sure that the task will no longer execute.\nscheduler.clearTimeoutOrInterval(handle: ITimerHandle): void\n```\n\n**Pros:**\n\n- A task is scheduled exactly to the second of the next cron date.\n\n**Cons:**\n\n- There is one timer per task, which could lead to lower performance compared to the interval based scheduler if you have many scheduled tasks.\n\n### 2. Interval based scheduler\n\nThe interval based scheduler checks for due task in a fixed interval. So there is only one interval for all tasks assigned to a scheduler.\nYou can have multiple instances of an interval based scheduler.\n\n```ts\n// Import the scheduler.\nimport { IntervalBasedCronScheduler } from 'cron-schedule/schedulers/interval-based.js'\n\n// Instantiate a new instance of the scheduler with the given interval. In this example, the scheduler would check every 60 seconds.\nconst scheduler = new IntervalBasedCronScheduler(60 * 1000)\n\n// Register a new task that will be executed on every future cron date, or only on the next cron date if isOneTimeTask is true.\n// An optional errorHandler can be provided, which is called when the task throws an error or returns a promise that gets rejected.\n// The task remains scheduled when an error occurs (if not a one time task). Tasks are at max executed only once per interval.\n// Returns an id to be used with unregisterTask.\nscheduler.registerTask(cron: Cron, task: () =\u003e unknown, opts?: { isOneTimeTask?: boolean, errorHandler?: (err: Error) =\u003e unknown }): number\n\n// Unregister a task causing it to no longer be executed.\nscheduler.unregisterTask(id: number): void\n\n// You can stop the scheduler, which clears the interval.\nscheduler.stop()\n\n// You can start the scheduler after stopping it again. A newly created scheduler is started by default.\n// Tasks that were due while the scheduler was stopped will be executed on the next interval tick (but only a single time).\nscheduler.start()\n```\n\n**Pros:**\n\n- Only one interval for all tasks, which is quite performant.\n\n**Cons:**\n\n- Tasks are not executed exactly on the cron date.\n- Tasks can only be executed once per interval.\n\n**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.**\n\n## Cron expression format\n\n_cron_schedule_ uses the linux cron syntax as described [here](https://man7.org/linux/man-pages/man5/crontab.5.html) with the addition that you can optionally\nspecify seconds by prepending the minute field with another field.\n\n```\n┌───────────── second (0 - 59, optional)\n│ ┌───────────── minute (0 - 59)\n│ │ ┌───────────── hour (0 - 23)\n│ │ │ ┌───────────── day of month (1 - 31)\n│ │ │ │ ┌───────────── month (1 - 12)\n│ │ │ │ │ ┌───────────── weekday (0 - 7)\n* * * * * *\n```\n\nAll linux cron features are supported, including\n\n- lists\n- ranges\n- ranges in lists\n- step values\n- month names (jan,feb,... - case insensitive)\n- weekday names (mon,tue,... - case insensitive)\n- time nicknames (@yearly, @annually, @monthly, @weekly, @daily, @hourly - case insensitive)\n\n**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.**\n\n## Cron validation\n\nLooking 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](https://github.com/airfooox/cron-validate)!\n\nUse the `npm-cron-schedule` preset to validate that cron expressions are supported by _cron-schedule_.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fp4sca1%2Fcron-schedule","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fp4sca1%2Fcron-schedule","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fp4sca1%2Fcron-schedule/lists"}