Search code examples
javascriptnode.jsbotsnode-cron

node-cron not executing script on interval only console.log


On initial run, it'll run app.js however, on interval it skips over it. What might I be doing wrong here?

var cron = require('node-cron');

cron.schedule('*/10 * * * * *', function(){
    var shell = require('./app.js');
     commandList = [
        "node app.js"
        ]

        console.log('Bot successfully executed'); 

});

Log:

ec2-user:~/environment $ node forever.js
Bot successfully executed
You have already retweeted this Tweet.
You have already retweeted this Tweet.
Bot successfully executed
Bot successfully executed
Bot successfully executed
Bot successfully executed
Bot successfully executed
Bot successfully executed
Bot successfully executed
Bot successfully executed

Solution

  • I guess your app.js executes the code immediately, so it is executed only by requiring it (and require is cached, so it is executed only once).

    You should return function from your app.js instead and call that on every run.

    // app.js
    module.exports = () => { 
        // your original code here
    };
    
    // forever.js
    var cron = require('node-cron');
    var shell = require('./app.js');
    
    cron.schedule('*/10 * * * * *', function(){
        shell();
    
        console.log('Bot successfully executed');
    });
    

    Or maybe you could clear the require cache before running:

    delete require.cache[require.resolve('./app.js')]