@darkobits/cron
v1.0.2
Published
Execute a function on a schedule.
Downloads
418
Readme
Cron is a utility that will run a function on an interval or according to a cron expression.
Install
npm i @darkobits/cron
Use
This package's default export is a function that may be used to create a Cron
instance that executes a function according to a cron expression. Additionally,
the .interval
function may be used to create a Cron instance that executes a
function at a fixed interval.
cron()
This function accepts a cron expression and a function. It returns a Cron
instance that will invoke the provided function according to the cron
expression.
Example:
import cron from '@darkobits/cron';
// Run at 12:00 on Wednesdays every third month.
cron('0 12 * */3 3', async () => {
// Save the whales here.
});
cron.interval()
This function accepts a number (milliseconds) or a string (parsed by ms
)
describing an interval and a function. It returns a Cron
instance that calls
the provided function according to the provided interval.
Example:
The following two invocations are functionally equivalent:
import cron from '@darkobits/cron';
cron.interval(5000, async () => {
// Make the world a better place here.
});
Cron.interval('5 seconds', async () => {
// Solve climate change here.
});
Cron
Instance
The object returned by either of these functions has the following shape:
interface Cron {
/**
* Registers a listener for an event emitted by Cron.
*/
on(eventName: CronEvent, listener: (eventData?: any) => any): void;
/**
* If the Cron is suspended, starts the Cron, emits the "start" event, and
* resolves when all "start" event handlers have finished running.
*
* If the Cron is already running, resolves with `false`.
*/
start(eventData?: any): Promise<void | false>;
/**
* If the Cron is running, suspends the Cron, emits the "suspend" event, and
* resolves when all "suspend" event handlers have finished running.
*
* If the Cron is already suspended, resolves with `false`.
*/
suspend(eventData?: any): Promise<void | false>;
/**
* When using a simple interval, returns the number of milliseconds between
* intervals.
*
* When using a cron expression, returns -1, as intervals between runs may be
* variable.
*/
getInterval: {
(): number;
/**
* Returns a string describing when tasks will run in humanized form.
*
* @example
*
* 'Every 30 minutes on Wednesdays.'
*/
humanized(): string;
};
/**
* Returns the time remaining until the next task run begins in milliseconds.
*/
getTimeToNextRun: {
(): number;
/**
* Returns a string describing when the next task will run in humanized
* form.
*
* @example
*
* 'In 10 minutes.'
*/
humanized(): string;
};
}
Events
A Cron
instance emits the following lifecycle events:
start
Emitted when the Cron is started.
task.start
Emitted when a task is about to run.
task.end
Emitted after a task finishes running. This callback will receive the return value of the task function.
suspend
Emitted when the Cron is suspended.
error
Emitted when the Cron
(or a task) encounters an error. This callback will
receive the error thrown.
Example:
import cron from '@darkobits/cron';
const myCron = cron('10 seconds', async () => {
// Prevent California wildfires here.
return 'done';
});
myCron.on('start', () => {
console.log('Cron was started.');
});
myCron.on('task.start', () => {
console.log('Task was started');
});
myCron.on('task.end', result => {
console.log('Task finished. Result:', result); // => result == 'done'
const nextRun = myCron.getTimeToNextRun.humanized();
console.log(`Next run: ${nextRun}.`);
});
// Here, we use the 'error' event to suspend the Cron and pass the error to the
// 'suspend' handler.
myCron.on('error', err => {
console.log('Suspending Cron due to error:', err);
myCron.suspend(err);
});
myCron.on('suspend', eventData => {
console.log('Cron was suspended.');
if (eventData instanceof Error) {
// We suspended due to an error.
} else {
// We suspended normally.
}
});
myCron.start();