npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@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();