I need to execute a shell script every hour. However I don't want to start the next run till the previous one is complete.


Since you tagged the question as Linux, you can use flock to put a lock on a well-known file:

flock "${TMPDIR:-/tmp}"/some_name.lock /path/to/your_command -options

A second instance of the command (run the same way) will wait until the first instance has finished. The problem with this approach is, if the command regularly takes more than an hour you'll just accumulate more and more instances waiting for the lock.

Alternatively, you can just skip running a second instance if the first hasn't finished:

flock -n "${TMPDIR:-/tmp}"/some_name.lock /path/to/your_command -options

The problem with this approach is you may run the command fewer that 24 times per day.


You need to define your problem better.

Sato has described how a method where new instances will back up behind a delayed one.

Jaroslav's solution only provides a mechanism for detecting that the previous instance has not yet finished cleanly.

Another option would be to schedule the next instance of the script inside the script itself:

at now + 1 hour $*

You need to define the behaviour if the previous instance has not completed, and whether you want instances to start at hourly intervals or within a defined interval between completion and start.

  • Thanks, Sato solution is solving my problem. Mostly my jobs will complete in an hour. However if not then I wants to wait for certain time. – puneet gupta Nov 4 '17 at 18:11

You can create some temporary file on script start and delete it before script close. The script should check for existence of that file. If it finds it, it'd just close and do nothing. If it doesn't, create it and continue.

Or in the cron job, you can use pgrep for checking the script being executed and continue only if it doesn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.