Running a Node.js script at regular intervals can be crucial for many applications, such as periodic data processing, regular updates, or scheduled maintenance tasks. While PM2 is an excellent tool for managing Node.js applications, it doesn't directly support scheduling tasks at specific intervals.

By combining PM2 with the node-cron module, you can easily achieve this functionality. In this blog post, I'll walk you through the steps to set this up.

  1. Install PM2 and node-cron

terminal

Copy
npm install -g pm2

terminal

Copy
npm install node-cron
  1. Create a simple Node.js script that you want to run at intervals. Let's call this script script.js.

JavaScript

Copy
// script.js console.log('This script is running at interval!');
  1. Create another script to handle the scheduling. This script will use node-cron to schedule the execution of your script.js. Let's call this scheduler.js.

JavaScript

Copy
// scheduler.js const cron = require('node-cron'); const { exec } = require('child_process'); // Schedule tasks to be run on the server. cron.schedule('*/5 * * * * *', () => { // Adjust the cron expression as needed // Can use this online tool https://crontab.guru/ console.log('Running a task every 5 seconds'); exec('pm2 start script.js --name my-script --no-autorestart', (err, stdout, stderr) => { if (err) { console.error(`Error executing script: ${err}`); return; } }); });
  1. Now start the scheduler

terminal

Copy
pm2 start scheduler.js --name scheduler
  1. Check PM2 status to ensure your scripts are running correctly

terminal

Copy
pm2 status
  1. Check PM2 logs to see the console messages.

terminal

Copy
pm2 logs

That's all.