Wednesday, 24 May 2017

Using node-schedule from another component/js

I'm trying to understand javascript and cron. I need to 'update' variable every n second(s). Here's the example:

/*===cron.js===*/
    var schedule = require('node-schedule')

    var hello = initHello()

    function initHello () {
        return 'hello'
    }

    function changeHelloToWorld () {
        return 'world'
    }

    function cron () {
        //change value to 'world' after n second(s)
        schedule.scheduleJob('*/10 * * * * *', function () {
            hello = changeHelloToWorld()
            return hello
        })
        return hello
    }


    module.exports = {
        cron
    }

/*===index.js===*/
var Hello = require('./cron')
var schedule = require('node-schedule');

//if I use this, it works. It prints 'world' instead of 'hello' after n seconds
schedule.scheduleJob('*/1 * * * * *', function () {
    console.log(Hello.cron())
})

//But if I use this, it doesn't work.
while (true) {
    console.log(Hello.cron())
}

From the example above, my question is, how can I get new value from cron.js without using scheduleJob() in index.js?



via S-audade

No comments:

Post a Comment