3

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
CodeSpent
  • 1,684
  • 4
  • 23
  • 46

1 Answers1

3

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')]

Martin Adámek
  • 16,771
  • 5
  • 45
  • 64
  • That did the trick. What ultimately allowed this to work? I tried a simple return with no luck. – CodeSpent Apr 26 '18 at 19:28
  • You mean `return` from `app.js`, without the `module.exports` part? – Martin Adámek Apr 26 '18 at 19:29
  • 1
    Well this solution works because you return a function when you require `app.js`, not executing the code. Then you can call that function multiple times. `module.exports` part is how node modules work (what you assign to that will be exported = returned from `require()` call) – Martin Adámek Apr 26 '18 at 19:33
  • Ohhhh I see what you're saying. Thanks for the help! I sat here fighting for a good 45 minutes, should have asked a bit sooner. – CodeSpent Apr 26 '18 at 19:41