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.
- Install PM2 and node-cron
terminal
Copynpm install -g pm2
terminal
Copynpm install node-cron
- 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!');
- 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; } }); });
- Now start the scheduler
terminal
Copypm2 start scheduler.js --name scheduler
- Check PM2 status to ensure your scripts are running correctly
terminal
Copypm2 status
- Check PM2 logs to see the console messages.
terminal
Copypm2 logs
That's all.