简体   繁体   English

使用 PM2 时如何仅在一个实例中运行代码?

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

I use PM2 to control and manage node.js processes.我使用 PM2 来控制和管理 node.js 进程。 With PM2 i run multiple instances of the application at the same time.使用 PM2,我可以同时运行应用程序的多个实例。 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?我想知道我是否可以将某个代码的执行限制为 1 个实例? 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您可以使用 NODE_APP_INSTANCE 环境变量来执行此操作: https://pm2.keymetrics.io/docs/usage/environment/#node_app_instance-pm2-25-minimum

Then in your NodeJS script you can have the following check:然后在您的 NodeJS 脚本中,您可以进行以下检查:

 // 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.恐怕用 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 .也许这个库可以帮助你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 PS:我是图书馆的作者

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.不过,您可以参考此备忘单了解最常用的pm2命令。 Maybe it has the straight answer to what you are searching.也许它对您正在搜索的内容有直接的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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