Ali Sherafat
Ali Sherafat

Reputation: 3855

Handling js intervals and cron jobs using pm2

I'm running a node app(with Express framework) using pm2 start ./bin/www -i 8 which runs 8 instances of application, so far so good.
in one of my files i'm using interval to query database every minute.

setInterval(function () {
    // db query
}, 60000); // every minute

with this approach i'm querying database 8 times per minute(because of 8 instance of app is running) but i want to query 1 time per minute.

should i write a separete script for running intervals and cron jobs without pm2?

how to handle this?

Upvotes: 0

Views: 940

Answers (1)

Ali Sherafat
Ali Sherafat

Reputation: 3855

As Ronald mentioned in comments above, we can check the main running app number using process.env.NODE_APP_INSTANCE === 0.

if (process.env.NODE_APP_INSTANCE === 0){
    // run cron jobs or etc here 
}

Upvotes: 3

Related Questions