简体   繁体   中英

Execute node app in the background as service (without routes) with pm2

I'm starting to tinker with node.js server, I created a node application which keeps a database in sync, the function of this app/script is to run an async function in 5 minutes intervals, for this I'm using node-cron, so far I got it to work after I visit my express route / .

Issue is I don't want to have to visit a route to start/stop/whatever the cron job, I have read about pm2 and would like to be able to execute my application as background with it.

Ideally I'd start and stop the cron job from the command line, where can I find a tutorial on how to do this in an ubuntu server?

My app.js file looks like this:

var express = require('express');
var app = express();
//process.env.DB_HOST

    app.get('/', async (req, res) => 
    {
        const job = new CronJob('0 */5 * * * *', function()
        {

            try
            {
                const databaseService = new DatabaseService();
                databaseService.syncDB();
            }
            catch(err)
            {
                console.error(err);
            }
        });

        job.start();
            
        res.send('Hello world');
    });


    app.listen(3000, function() 
    {
        console.log('Example app listening on port 3000!');
    });

How to handle cron job without visiting route/script running from console in the background

If you want node to manage just the cronjob, remove express

const job = new CronJob('0 */5 * * * *', function(){
    try
    {
        const databaseService = new DatabaseService();
        databaseService.syncDB();
    }
    catch(err)
    {
        console.error(err);
    }
});

job.start();

As @Randy Casburn mentioned, you can just run the database sync function in node and have the cron daemon schedule that for you instead of using pm2 to manage a long running node process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM