Set Interval in Node.js vs. Cron Job?

邮差的信 提交于 2019-11-27 20:32:36

问题


I'm learning node.js and just set up an empty Linux Virtual Machine and installed node.

I'm running a function constantly every minute

var request = require('request')
var minutes = 1, the_interval = minutes * 60 * 1000

setInterval(function() {
    // Run code
  })
}, the_interval);

And considering adding some other functions based on current time. - (e.g. run function if dateTime = Sunday at noon)

My question is are there any disadvantages to running a set up like this compared to a traditional cron job set up?

Keep in mind I have to run this function in node every minute anyways.


回答1:


It depends on how strictly you have to adhere to that minute interval and if your node script is doing anything else in the meantime. If the only thing the script does is run something every X, I would strongly consider just having your node script do X instead, and scheduling it using the appropriate operating system scheduler.

If you build and run this in node, you have to manage the lifecycle of the app and make sure it's running, recover from crashes, etc. Just executing once a minute via CRON is much more straightforward and in my opinion conforms more to the Unix Philosophy.




回答2:


My question is are there any disadvantages to running a set up like this compared to a traditional cron job set up?

As long as //run the code isn't a CPU-bound thing like cryptography, stick with 1 node process, at least to start. Since you are requiring request I guess you might be making an HTTP request, which is IO, which means this will be fine.

It's just simpler to have 1 thing to install/launch/start/stop/upgrade/connect-a-debugger than to deal with an app server as well as a separate cron-managed process. For what it's worth, keeping it in javascript makes it portable across platforms, although that probably doesn't really matter.

There is also a handy node-cron module which I have used as well as approximately one bazillion other alternatives.



来源:https://stackoverflow.com/questions/18120909/set-interval-in-node-js-vs-cron-job

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!