cron Vs. sleep - which is the better one in terms of efficient cpu/memory utilization?
Use cron
(or anacron
).
Cron is designed for running things at intervals. That is the only thing it does, and there has been a lot of work put into cron for many years to make it what it is today.
The chances that you're going to write a better scheduler in your script are effectively nil. Using cron will work better, avoid having unnecessary code in your script and keep your code concise and more maintainable.
Do not reinvent the wheel if you do not have to.
Use cron because it is a better and more standard practice. At least if this is something that will regularly run (not just something you patched together in a minute). cron
is a cleaner and more standard way. It's also better because it runs the shell detached from a terminal - no problem with accidental termination and dependencies on other processes.
Regarding the resources:
CPU: Both processes sleep - when they sleep, they do not waste CPU. cron
wakes up more frequently to check on things, but it does that anyway (no more for your process). And this is negligible load, most daemons wake up occasionally.
Memory: You probably have cron
running regardless of this process, so this is no overhead at all. However, cron will only start the shell when the script is called, whereas your script remains loaded in memory (a bash process with environment - a few kilobytes, unless you are loading everything in shell variables).
All in all, for resources it doesn't matter.
There are already some good answers on cron
and sleep
performance, but I want to add some kind of feature comparison.
Pro cron
:
- running already on Unix/Linux systems
- stable and proven
- designed for background processes
- runs from system start-up onward, and so will your script, once installed
- easier entry of long-term cycles (hours, days, weeks)
- allows complex long-term repeats ("every second Sunday at 5:35 a.m.")
Pro sleep
:
- easier to maintain in a script
- easier for foreground processes
- allows sleep times shorter and more precise than a minute
- allows complex sleep/action cycles ("run this part, then sleep 10 seconds, then run the other part and sleep two hours")