简体   繁体   中英

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!

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

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.

Maybe this library can help you https://github.com/Tomas2D/pm2-master-process .

Usage is pretty simple:

import { isMasterInstance } from 'pm2-master-process'

if (await isMasterInstance()) {
  console.info(`I am master!`)
} else {
  console.info(`I am a slave.`)
}

PS: I am the author of the library

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM