1

I need to find a cron command that would restart pm2 with a process but only if it's not already running

pm2 start app.js starts the app even if it's already running.

what would be another command I could use that would only restart app.js if it's not already running and how would I write it in crontab?

Aerodynamika
  • 7,883
  • 16
  • 78
  • 137
  • Possible duplicate of [Is there a way to restart pm2 process using cron but only if it's not already running?](https://stackoverflow.com/questions/48872352/is-there-a-way-to-restart-pm2-process-using-cron-but-only-if-its-not-already-ru) – Aydin K. Feb 28 '18 at 09:48

1 Answers1

1

There is no default way in pm2 to achieve this instead of that you can write a shell script for that.

#!/bin/bash

pm2 describe appname > /dev/null 
RUNNING=$?  

if [ "${RUNNING}" -ne 0 ]; then
    pm2 start ./yourscriptpath
else
    pm2 restart appname
fi;

Save this shell script as pm2_starter.sh and then

crontab -e

and add following there

 */30 * * * * ./home/ridham/stackoverflow/pm2_starter.sh

this will run it every 30 minutes.

Here the script will restart if app is running under pm2 and else it will start it. You are smart enough to edit that as per your use case

Ridham Tarpara
  • 5,970
  • 4
  • 19
  • 39
  • Thanks! Why do you use `-ne` though? If the app is not running I want it to start, but if it's running I want it not to do anything. So what operator would I use? `-eq` and remove the `else` statement? – Aerodynamika Feb 28 '18 at 11:27
  • Plus even if pm2 is running the `RUNNING` variable is still `0` so probably it needs a different check? – Aerodynamika Feb 28 '18 at 11:30
  • yeah RUNNING will return non zero value if app is not found in the pm2 list. – Ridham Tarpara Feb 28 '18 at 13:17