Cron is a utility that will run a function on an interval or according to a cron expression.
npm i @darkobits/cron
This package's default export is a factory function that accepts an options object of the following shape:
The object returned by Cron has the following shape:
Simple Intervals vs. Cron Expressions
When using a simple interval with Cron (ex:
10 seconds), Cron will run its task, and then wait 10 seconds before running its task again. Therefore, if a task takes on average 20 seconds to complete, Cron will start new task runs approximately every 30 seconds. This prevents concurrent task runs that may lead to race conditions or unintended side-effects.
However, when using a cron expression (ex:
0 * * * *, or every hour), Cron will always begin a new task run at the top of the hour, whether or not the last task run has finished. It is therefore up to the developer to understand approximately how long their tasks take and how often to execute them to avoid concurrent task runs.
Cron emits the following events:
Emitted when the Cron is started.
Emitted when a task is about to run.
Emitted after a task finishes running. This callback will receive the return value of the task function.
Emitted when the Cron is suspended.
Emitted when the Cron (or a task) encounters an error. This callback will receive the error thrown.
Using a simple interval:
Using a cron expression:
;;// Run at 12:00 on Wednesdays during every third month.;cron.start;
Setting up event handlers: