简体   繁体   中英

Restart with PM2 API, restarts also the script self, when running in PM2

I want to make a script in Javascript which controlls PM2 via the PM2 API, and also runs in PM2.

pm2.js

var pm2 = require('pm2');

setTimeout(() => {
  restartProcess('client');
}, 2000); //After 2 seconds restart the 'client' process

function restartProcess(name) {

  pm2.connect(function(err) {
    if (err) {
      console.error(err);
      process.exit(2);
    }
    console.log ("restarting ",name)
    pm2.restart(name);

  pm2.disconnect;  
  })
  
}

When I run pm2.js only in the terminal, this works okay. But when I run pm2.js inside PM2, the script keeps looping. I checked the uptime of the processes, it seems that not only client restarts but also pm2.js itself restarts, and after 2 seconds again, and again, and again...

If I'm lookings at pm2 logs pm2 I see there in de stdout the pm2 list table. Which I don't see if I run pm2.js from the terminal.

I don't understand why this happens, and is there a workarround to fix this?

Why would you want to do that?

PM2 is a daemon process manager that will help you manage and keep your application online 24/7

Please check the official document first. PM2 was designed to manage long-running tasks, somethings like a web server. If the web server crashes or exits by any reasons, pm2 will interfere and wake it up again. That's the default behavior.

Your pm2.js just run in a short time (2 seconds) then exit. So if you start it with PM2, it will be started again and again...

There is no reason to run that script inside PM2. If you still want, then run it with --no-autorestart flag.

You can send SIGKILL to your service, then PM2 will start it again.

pm2.connect((err) => {
    pm2.sendSignalToProcessName('SIGKILL', name, (e, p) => {
        pm2.disconnect();
    });
});

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