Search code examples
node.jsservernode-cron

node-cron only working with an active session


I have a simple node-cron schedule that calls a function:

cron.schedule('00 00 00 * * *', () => {
  console.log('update movies', new Date().toISOString());
  updateMovies();
});

When I log in to my server using PuTTy or use the droplet console in Digital Ocean and then run the updateMovies.mjs file node server/updateMovies.mjs and wait for the time that the cron-job should run, everything works as expected.

But when I close PuTTy or the droplet console in Digital Ocean, then nothing happens when the cron-job should run. So the server seems to lose the cron-job when I close the session.


Solution

  • Short answer

    You need to run the app in the background

    nohup node server/updateMovies.mjs >/dev/null 2>&1 
    

    Long answer

    Run your app directly in the shell is just for demos or academic purposes. On an enterprise environment you should a live process like a server which runs independently of the shell user.

    Foreground and background processes

    • Processes that require a user to start them or to interact with them are called foreground processes
    • Processes that are run independently of a user are referred to as background processes.

    How run background process (Linux)

    No body uses windows for an modern deployments, so in Linux the usual strategy is to use nohup

    server.js

    var express = require('express');
    var app = express();
    
    app.get('/', function(req, res) {
      res.type('text/plain');
      res.send('Hell , its about time!!');
    });
    
    app.listen(process.env.PORT || 8080);
    
    nohup node server.js >/dev/null 2>&1 
    

    If you login to the server using some shell client, and run only node server.js it will start but if you close the shell window, the process will ends.

    enter image description here

    How run background process with nodejs and PM2

    pm2 server.js
    

    More details here:

    https://pm2.keymetrics.io/docs/usage/quick-start/

    Best way : Docker

    You need to dockerize your app and it will run everywhere with this command:

    docker run -d my_app_nodejs ....