Cron jon NodeJS with node-cron

Tram Ho

When developing an application there are things that need to be performed periodically over time such as statistics, aggregation, data synchronization or recurring tasks like sending daily reminder emails. We need a good solution for this! And today I want to introduce to you a module to create run jobs on a simple and efficient schedule.

Node-cron is a module for creating scheduled sub-tasks using native JavaScript based on the GNU crontab . This module allows you to schedule tasks in node.js using full crontab syntax.

Install and use node-cron

  • Install node-cron via npm

npm install –save node-cron

Also you can install node-cron through the responsitory guests like yarn.

  • Import and create a cron job using node-cron

crontab syntax

Each crontab usually has the structure:

Range of allowed values

SchoolValue range
Day in month1-31
Month1-12 or JAN-DEC
Day of the week0-7 or SUN-SAT (0 or 7 is a Sunday)

Special characters are available

*(all value) is used where all values ​​are true.
(range of values ​​-) is used to describe the range of values
,(value list separator) is used to list values
/(step values) are used to specify the number of increments

Some common Tips

0 * * * *: Runs at 00 minutes of each hour.

1,2,4,5 * * * *: Run every minute 1,2,4 or 5.

Some functions are provided by node-cron

Ingredients of a cron

  • expression string: Cron operator
  • function Function: The function performs by schedule
  • options Object: Optional.

Options scheduled boolean: true if the task has been changed. Default is true; timezone string: time zone;

A full cron function:

Functions are provided

Start Starts creating a schedule for a task.

Stop Creates a stop from executing a schedule for a task.

Destroy Cancels a schedule for a task.

Validate Validate the validity of a cron operator.

Reference sources: , html

Share the news now

Source : Viblo