Reputation: 19651
I am using PM2
to keep my node.js apps running.
Is there any way to have PM2
restart my app every 1 hour?
Upvotes: 8
Views: 27844
Reputation: 5027
You can now use the pm2 built-in --cron-restart
option, documented here. In your case, to restart every hour, you could add this to your pm2 config file.
cron_restart: '0 * * * *',
Upvotes: 7
Reputation: 7988
Here is how I did it. Then: pm2 start name_of_your_file.js
.
In my case, it will exit the script after 15 minutes.
/**************************************************************************
* IMPORTS
***************************************************************************/
// NPM
const consola = require('consola')
const pm2 = require('pm2')
/**************************************************************************
* START PM2 PROGRAMATICALLY
***************************************************************************/
pm2.connect((error) => {
if (error) {
console.error(error)
process.exit(2)
}
pm2.start({ script: 'brain/domains.js' }, (error, apps) => {
pm2.disconnect() // Disconnects from PM2
if (error) {
console.error(error)
process.exit(2)
}
})
// Kill the process if taking longer than expected
setInterval(() => {
pm2.describe('domains', (error, scripts) => {
const exitTimeout = 15
const uptime = Date.now() - scripts[0].pm2_env.pm_uptime
if (uptime > exitTimeout * 60 * 1000) {
consola.info(`Closing cluster after ${exitTimeout} minutes...`)
pm2.restart('domains', (error) => {
if (error) {
console.error(error)
process.exit(2)
}
})
}
})
}, 30 * 1000)
})
Upvotes: 0
Reputation: 501
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
Upvotes: 4
Reputation: 3128
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:
Upvotes: 9