How can I block a cron job when the previous run was not finished. Its a cron job which is running every 5 minutes, but sometimes it needs more than 5 minutes to run.
Edit The script which is called, crashes sometimes! So it can not delete lock file.
Use
flock(1)
:You can have it block or immediately exit. Pre-existence (or absence) of the lock file doesn't make a difference. It creates the file if needed and uses a
flock()
system call to lock the file. This lock is automatically released at process death.For example, in cron:
If your jobs don't always finish in 5 minutes, you might consider using
--timeout
so that your jobs don't queue up:Or use
--nonblock
to exit immediately -- it would be similar to--timeout=0
If your script is a shell script, you can use some clever redirection tricks to use flock within your script itself:
Or, the manual also suggests making your script recursive by putting this at the top (it uses the script itself as its lock file):
See the
flock(1)
man page for more informationPid files are the way to go, however, much like init scripts don't just give up when they see a pid file, you should check to ensure that the pid in the file still exists.
Something like this would do the trick:
Checking for pid or lock file can fail when the cron job fails to clean the file after exit. I see the better option is to check for the process itself such as:
This will give you the number of processes that have the name 'script_name'. You can check this count at the beginning of your script execution.
You can't, cronjobs don't come with this functionality. Put something in your script to check for it, or have it create a file when finished and use something such as inotifywait to block.
Look for a file in e.g.
/var/run
. If the file is found then exit. Otherwise, create the file, run your routine, and then remove the file.There are many ways. Popular one is to use a lock file.
1) When the script starts, it checks if a lock file (like
/var/lock/powtac.loc
) already presents.2) If it does exist, script aborts, assuming the previous script is still running *).
3) If it does not exist, script creates the file and continues to do whatever it needs to do.
4) Upon exit, script deletes the lock file.
*) It would also be possible to check the process list at this point, search for matches for your cron job and if found, see when they were started. If recently, then assume they are still running, if loooooooooong time ago, then assume they were stuck.
I wouldn't have two cron jobs I'd have one.
It will only run if the first command completes successfully, and only after it's done.
( note: if you need it to be a few minutes after use
sleep
)