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.
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.
Use case: Run the app.py at every 3rd minute.
https://github.com/jessety/pm2-installer
pm2 start app.py --cron "*/3 * * * *" --no-autorestart --time
pm2 save
Restart Windows and check.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With