sbs
sbs

Reputation: 4152

bash shell script sleep or cronjob which is preferred?

I want to do a task every 5 mins. I want to control when i can start and when i can end.

One way is to use sleep in a while true loop, another way is to use cronjob. Which one is preferred performance-wise?

Thanks!

Upvotes: 2

Views: 2735

Answers (2)

rici
rici

Reputation: 241671

cron is almost always the best solution.

If you try to do it yourself with a simple script running in a while loop:

while true; do
  task
  sleep 300
done

you eventually find that nothing is happening because your task failed due to a transient error. Or the system rebooted. Or some such. Making your script robust enough to deal with all these eventualities is hard work, and unnecessary. That's what cron is for, after all.

Also, if the task takes some non-trivial amount of time, the above simple-minded while loop will slowly shift out of sync with the clock. That could be fixed:

while true; do
  task
  sleep $((300 - $(date +%s) % 300))
done

Again, it's hardly worth it since cron will do that for you, too. However, cron will not save you from starting the task before the previous invocation finished, if the previous invocation got stuck somehow. So it's not a completely free ride, but it still provides you with some additional robustness.

A simple approach to solving the stuck-task problem is to use the flock utility. For example, you could cron a script containing the following:

(
  flock -n 8 || { 
    logger -p user.warning Task is taking too long
    # You might want to kill the stuck task here. See pkill
    exit 1
  }
  # Do the task here
) 8> /tmp/my_task.lck

Upvotes: 3

Kai Sternad
Kai Sternad

Reputation: 22830

Use a cron job. Cron is made for this type of use case. It frees you of having to to code the while loop yourself.

However, cron may be unsuitable if the run time of the script is unpredictable and exceeds the timer schedule.

Performance-wise It is hard to tell unless you share what the script does and how often it does it. But generally speaking, neither option should have a negative impact on performance.

Upvotes: 3

Related Questions