Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node-schedule callback function in node.js

So I'm using https://npmjs.org/package/node-schedule to schedule some tasks, somewhat new to node.js and I don't understand why creating a function 'in line' works while defining a function and calling it does not schedule correctly, it just runs instantly and then quits.

job = schedule.scheduleJob({}, function (){console.log('one minute')});

works, but

function test(){
    console.log('one minute')
}
job = schedule.scheduleJob({}, test);

fires once and exits.

like image 286
user2743766 Avatar asked Aug 23 '26 20:08

user2743766


1 Answers

function(){.....} creates a pointer to an anonymous function which is evaluated when the scheduled timeout expires. A direct call is evaluated immediately because it is NOT a function pointer; essentially, the program is trying to evaluate it in case the function returns a pointer it can store and access later (return function(){.....}). The behaviour you want can be simulated by either setting the callback to

function(){test()}

or changing the body of test to:

return function(){console.log('one minute')};

You can simulate this behaviour in a browser window by using the setInterval and setTimeout methods; They are what node-schedule uses internally to schedule tasks.

like image 109
mydnight Avatar answered Aug 27 '26 00:08

mydnight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!