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

schedule-jobs-with-cron

v1.5.4

Published

Schedule jobs with cron specifications

Downloads

50

Readme

schedule-jobs-with-cron

Schedule jobs in NodeJs using cron specifications

Why?

  • Support async worker function and compatible with non-async too
  • Works with standard crontab definitions
  • Cron parser shows the schedule in plain english
  • Typescript support
  • Zero dependencies
  • Small (Less than 45 KB when installed from NPM)
  • Configurable
  • Other good cron packages haven't been updated in a while

CodeQL DevSkim ESLint

How to use basics:

Install it from npm:

npm i schedule-jobs-with-cron

To use it:

import { CronJob } from 'schedule-jobs-with-cron';

// Define and schedule a new job
const job1 = new CronJob(
  'A test Job 1',
  (triggerTime, log) => {
    log('info', `Hello from inside the job, it was triggered at: ${triggerTime}`);
    // Add code that does some work here
  },
  '*/2 * * * *',
);

// Await for the job
await job1.getPromise();

Explanation:

The above creates a new scheduled job, passing in a name (it can be named anything), next is the worker function that will be triggered, and a standard cron schedule specification to use, in this case it's */2 * * * * which will run every 2 minutes.
(The website https://crontab.guru is helpful to define cron schedules.)

Optionally the parsed cron specification can be printed out in english like this:

job1.englishDescriptionOfCronSchedule;

As long as the job promise is awaited the job will continue to run and be rescheduled forever, unless an endDate is provided through the optional parameters (more on that below).

The console output of the above will look like the following example:

Job [A test Job 1]: Scheduled to execute: At every 2nd minute
Job [A test Job 1]: Scheduling to trigger in the next 81699 ms, at (Sat Jan 07 2023 04:24:00 GMT-0500 (Eastern Standard Time)) the time is now Sat Jan 07 2023 04:22:38 GMT-0500 (Eastern Standard Time).
Job [A test Job 1]: Hello from inside the job, it was triggered at: Sat Jan 07 2023 04:24:00 GMT-0500 (Eastern Standard Time)
Job [A test Job 1]: Scheduled trigger finished!
Job [A test Job 1]: Scheduling to trigger in the next 119997 ms, at (Sat Jan 07 2023 04:26:00 GMT-0500 (Eastern Standard Time)) the time is now Sat Jan 07 2023 04:24:00 GMT-0500 (Eastern Standard Time).

Documentation:

The cron job is initialized by creating a new instance of the class CronJob. There is no limit to the number of jobs that can be created. The constructor of CronJob takes the following parameters:

const exampleJob = new CronJob(param1, param2, param3, param4);

param1:

  • String naming the job so that it is easier to distinguish in logs.

param2:

  • Callback worker function that can be either an async function or a simple plain function

  • Optionally the function can make use of the triggerTime and the internal logger if desired to log things out in a consistent manner by passing a function with the following signature:

    (triggerTime, log) => Promise<void> | void

param3:

  • String representation of a standard cron spec. It may be helpful to use the online tool https://crontab.guru/ in assisting to compose a cron spec. The format of a standard cron spec is five parts separated by spaces

    example * * * * *

    cronspec.png

  • Here are some examples:

    • 5 4 * * * = At 04:05 every day

    • 15 */4 2 4 2 = At minute 15 past every 4th hour on day-of-month 2 and on Tuesday in April

    • 0 22 * * 1-5 = At 22:00 and on every day-of-week from Monday through Friday

    • 23 0-20/2 * * * = At minute 23 past every 2nd hour from 0 through 20

    • 0 0,12 1 */2 * = At minute 0 past hour 0 and 12 on day-of-month 1 in every 2nd month

    • 0 4 8-14 * * = At 04:00 on every day-of-month from 8 through 14

    • 0 0 1,15 * 3 = At 00:00 on day-of-month 1 and 15 and on Wednesday

  • Note that you can use the job property .englishDescriptionOfCronSchedule anytime to print out an english interpreted text of the cron spec that was used to initialize the job.

param4:

  • Optional additional configuration as a JSON object:

    {
      /**
       * The number of scheduled iterations the scheduler should execute.
       * For example, if the schedule is once every minute, and
       * the number of iterations is set to 5, then it wll execute the worker
       * five times once every minute, after which the shedule will end.
       *
       * default is 0. Zero is special, it means there is no end.
       */
      numberOfScheduledIterationsToExecute: number
    
      /**
       * Optional specify wether to continue the job schedule if an
       * error occurs.
       * The default for this is false.
       */
      continueOnError: boolean
    
      /**
       * Optional date/time to specify when the job should stop executing.
       * When the job ends, the Promise returned by job.getPromise()
       * will be resolved.
       * The default for this is no end-date so it will run forever
       */
      endDate: Date
    
      /**
       * Optional date/time to specify when the job should begin executing
       * according to the schedule.
       * The default for this is current date time so the schedule
       * will being immediately.
       */
      startDate: Date
    
      /**
       * Disable logging that is generated by the job scheduler
       * or when using the log function passed into the jobWorkerFunction.
       * The default is false to enable logging.
       */
      disableLogging: boolean
    
      /**
       * Optional callback called after internally setting up timeout for
       * the next iteration of when the job is expected to trigger again.
       * This is typically useful for creating mocked
       * unit tests and not normally needed for normal operation,
       * but can be used for complex use cases if needed
       */
      afterSettingTimeoutCallback: (() => void)
    
      /**
       * Optional callback called just before triggering the
       * jobWorkerFunction. This is typically useful for creating mocked
       * unit tests and not normally needed for normal operation, but can
       * be used for complex use cases if needed.
       */
      beforeExecutingWorkerCallback: (() => void)
    }