Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to restart pm2 process using cron but only if it's not already running?

Tags:

node.js

pm2

I want to restart my Node.Js app using PM2 through

pm2 restart app.js

using crontab but ONLY if the app is not already running (e.g. if my server crashed and restarted and pm2 didn't restart).

the command above restarts it anyway even if it's running.

How do I fix it?

UPDATE

I do not want my app to restart if it's already running. I want it to restart only if it's listed as "stopped" or if it is not running. Some suggestions offer to write a bash script, but what would it be? I tried the options below, but they either don't work or restart the app even if it's running.

like image 974
Aerodynamika Avatar asked Feb 19 '18 18:02

Aerodynamika


2 Answers

For Linux

My use case: Run the app every 3 seconds.

Easy way:

pm2 startup This creates a command, copy and run it.

pm2 start app.js --restart-delay=3000 Each 3000 ms restart the app

pm2 save

Finally, reboot Linux and test.

For Windows

Use case: Run the app.py at every 3rd minute.

  1. https://github.com/jessety/pm2-installer

  2. pm2 start app.py --cron "*/3 * * * *" --no-autorestart --time

  3. pm2 save

Restart Windows and check.

More Info

  • https://pm2.keymetrics.io/docs/usage/startup/
  • https://pm2.keymetrics.io/docs/usage/restart-strategies/
like image 38
Hasan Gökçe Avatar answered Oct 01 '22 05:10

Hasan Gökçe


What you're looking to do is start any stopped apps without incurring downtime. A good solution is to use the pm2 startOrReload command. This will start any stopped apps, and will reload any current apps without incurring downtime.

You'll need a config file for the command. if you don't currently have one you can create it using pm2 ecosystem. Make sure it points to app.js.

Then run this command in your cron job:

pm2 startOrReload <your ecosystem file>

See pm2 -h, pm2 startOrReload -h, and pm2 ecosystem -h for more options.

like image 87
YPCrumble Avatar answered Oct 01 '22 05:10

YPCrumble