cron vs sleep which is better ?

The case

if you need to run scripts or commands at certain intervals of time, you have two options:

  • Use a cron job
  • Use a infinite loop with sleep in the scrpt itself

So what is the better option in terms of cpu/memory utilization and why ?

Pro cron:

  • running already on Linux systems
  • stable and proven
  • designed for background processes
  • 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”)

conclusion cron vs slepp

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.