node js cron example

The following is an example of how to use cron in Node.js. Each step is explained below:

Step 1: Install the 'node-cron' library by running the following command in your Node.js project directory:

npm install node-cron

Step 2: Require the 'node-cron' module in your Node.js file:

const cron = require('node-cron');

Step 3: Define a cron job by calling the cron.schedule() function and passing in the cron schedule as the first argument and a callback function as the second argument:

cron.schedule('/5  *', () => {
  // Your code here
});

In the example above, '/5 *' is the cron schedule, which means the cron job will run every 5 minutes. You can customize the cron schedule based on your requirements.

Step 4: Write the code that you want to execute at the specified schedule inside the callback function:

cron.schedule('/5  *', () => {
  console.log('This cron job runs every 5 minutes');
});

In this example, the code inside the callback function simply logs a message to the console every time the cron job runs.

Step 5: Start the cron job by calling the start() function:

cron.schedule('/5  *', () => {
  console.log('This cron job runs every 5 minutes');
}).start();

The start() function is used to begin executing the cron job based on the defined schedule.

That's it! Your cron job is now set up and will run at the specified schedule. You can add more cron jobs by repeating steps 3 to 5 with different cron schedules and code inside the callback functions. Remember to customize the cron schedule and code as per your requirements.