Emil
Emil

Reputation: 681

How to run code just in one instance when using PM2?

I use PM2 to control and manage node.js processes. With PM2 i run multiple instances of the application at the same time. The problem is that if you need to execute a specific code (task) only once, this code will be executed in each instance accordingly. I wonder if I can limit the execution of a certain code only to 1 instance? Is there any way to do this? Thank you!

Upvotes: 2

Views: 3012

Answers (3)

Yuriy Boev
Yuriy Boev

Reputation: 83

You can use NODE_APP_INSTANCE env variable to do this: https://pm2.keymetrics.io/docs/usage/environment/#node_app_instance-pm2-25-minimum

Then in your NodeJS script you can have the following check:

// Run script only on first PM2 instance
if (process.env.NODE_APP_INSTANCE === '0') {
    foo();
}

Regards

Upvotes: 7

Rost
Rost

Reputation: 72

I'm afraid that it's not possible to do that out of the box with pm2. You need to implement some sort of semaphore to track running instances count. Or get the part of the code you need to run once out of the main script and run it with scheduler.

Upvotes: 0

Abhishek Kumawat
Abhishek Kumawat

Reputation: 808

Your question could have been more clear and descriptive. Its a bit confusing.

Nevertheless, you can refer to this cheatsheet for most used pm2 commands. Maybe it has the straight answer to what you are searching.

Upvotes: -3

Related Questions