Skip to content

PM2 schedule tasks with node schedule

iot_pro edited this page May 19, 2018 · 1 revision
  • Create cron.js
const os = require('os');
const schedule = require('node-schedule');
 
// check if app is running with PM2
if (process.env && process.env.NODE_APP_INSTANCE) {
 
  //running in pm2
  if (process.env.NODE_APP_INSTANCE % os.cpus().length === 0) {
 
    schedule.scheduleJob('*/10 * * * * *', function () {
      console.log('running in one of the PM2 process.', new Date());
    });
 
  }
 
}else {
 
  // running without PM2
  schedule.scheduleJob('*/10 * * * * *', function () {
    console.log('running without PM2.', new Date());
  });
 
}
  • Run with PM2
pm2 start cron.js -i 0 --name cron

Clone this wiki locally