Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force pm2 to restart after a specific amount of time?

Tags:

node.js

pm2

I am using PM2 to keep my node.js apps running.

Is there any way to have PM2 restart my app every 1 hour?

like image 421
faressoft Avatar asked Jun 27 '16 19:06

faressoft


People also ask

How do I stop PM2 from auto restarting?

In this case, you can still use PM2 just fine with a stop_exit_codes option set to exit codes that should skip auto restart: Or via configuration file, use the stop_exit_codes attribute: A new restart mode has been implemented on PM2 Runtime, making your application restarts in a smarter way.

What's new in PM2 runtime?

A new restart mode has been implemented on PM2 Runtime, making your application restarts in a smarter way. Instead of restarting your application like crazy when exceptions happens.

How much does restart delay increase when running PM2 logs?

By running pm2 logs you will also see the restart delay being incremented: As you can see the restart delay between restarts will increase in an exponential moving average, till reaching the maximum of 15000ms between restarts.

How do I start PM2 from the command line?

$ pm2 startup upstart [PM2] You have to run this command as root. Execute the following command: sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup upstart -u vagrant --hp /home/vagrant Execute the generated command to daemonize PM2 and generate the system’s init script which is executed on boot.


2 Answers

Put the code below in pm2.js and start it with pm2 start pm2.js

    var pm2 = require('pm2');

  pm2.connect(function(err) {
    if (err) throw err;

  setTimeout(function worker() {
    console.log("Restarting app...");
    pm2.restart('app', function() {});
    setTimeout(worker, 1000);
    }, 1000);
  });

More about this can be found here.

Additional resources:

  • How can I programmatically shutdown a node program and restart it?
  • Programmatically watch and restart node server
like image 99
Tomislav Stankovic Avatar answered Nov 15 '22 02:11

Tomislav Stankovic


Use crontab.
Append this under your crontab file (run with crontab -e):

0 * * * * pm2 restart yourappname

Note that if you don't want to increment your pm2 restart counter, you can do something like this:

0 * * * * pm2 stop yourappname && pm2 start yourappname

Explanation:

0: on the 0th minute of the hour
*: every hour
*: every day
*: every month
*: every day of the week

like image 37
Binary Avatar answered Nov 15 '22 04:11

Binary