node.js - cron.js vs setInterval

javascript, node.js, npm

Solution

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 become 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.

Problem

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.

Original source