最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - node.js - cron.js vs setInterval - Stack Overflow

programmeradmin1浏览0评论

I need to run a couple of scripts every hour or every 30 minutes, and I also need to have control over them (restart, stop and start). I am currently using cron.js, however is there any performance difference if I use the native setInterval? instead of using the cron.js? Also, will I be able to have control over them?

The small scripts could be hundreds running at the same time, they modify data on a mongodb database.

I need to run a couple of scripts every hour or every 30 minutes, and I also need to have control over them (restart, stop and start). I am currently using cron.js, however is there any performance difference if I use the native setInterval? instead of using the cron.js? Also, will I be able to have control over them?

The small scripts could be hundreds running at the same time, they modify data on a mongodb database.

Share Improve this question asked Feb 14, 2014 at 15:41 DavidDavid 7091 gold badge9 silver badges22 bronze badges 1
  • What OS are the scripts running on? – srquinn Commented Feb 14, 2014 at 16:41
Add a ment  | 

1 Answer 1

Reset to default 11

I would highly suggest the use of your operating system's native crontab(1) program. I was once sucked into the simplicity of cron.js only to quickly realize that it is not very reliable in production.

is there any performance difference if I use the native setInterval?

Yes indeed. Because of the nature of the Javascript runtime, setInterval() is not accurate and will eventually bee out of sync with your operating system's clock. cron.js uses setInterval() under the covers, however, they add a heartbeat monitor to adjust the deltas between the interval and the cpu's clock found by utilizing the Date object. Neither method should be considered reliable if the accuracy in which the scripts run is crucial.

Also, using cron.js makes your timed scripts dependent on the process. Sure, you could use forever to keep the process up indefinitely, but if it happens to crash a couple seconds before the job is to execute, there is a strong possibility the script won't run as forever restarts. Not to mention, if the machine restarts, the forever process will die unless scheduled to restart on boot with upstart(1) or, ironically enough, crontab(1).

Summary:

crontab(1) is a battle tested program relied on by enterprise software for decades now. No point in reinventing the wheel =)

If you append a SheBang at the top of each script like so:

#! /usr/bin/env node

and set the file to be executable, you can register the script with crontab(1) like any old Bash script.

发布评论

评论列表(0)

  1. 暂无评论