I am looking for a simple and generic solution that would allow you to execute any script or application in crontab and prevent it from running twice.
The solution should be independent on the executed command.
I assume it should look like lock && (command ; unlock)
where lock will return false if there was another lock.
The second part would be like if it acquired the lock, run command and unlock after command is executed, even if it returns error.
Take a look at the
run-one
package. From the manpage for therun-one
command :Like
time
orsudo
, you just prepend it to the command. So a cronjob could look like:For more information and background, check out the blog post introducing it by Dustin Kirkland.
A very simple way of settup a lock:
A scripts which want to run needs te create the lock. If the lock exists, another script is busy, so the first script can't run. If the file don't exists, no script has acquired the lock. So the current script acquires the lock. When the script has finished the lock needs to be realeased by removeing the lock.
For more information about bash locks, check this page
See also Tim Kay's
solo
, which performs locking by binding a port on a loopback address unique to the user:http://timkay.com/solo/
In case his site goes down:
Usage:
Use it like this:
Script:
No need to install some fancy package:
It's faster to write that script yourself than to run "apt-get install", isn't it? You might want to add "-u $(id -u)" to the pgrep to check for instances run by the current user only.
You need a lock.
run-one
does the job, but you may also want to look intoflock
fromutil-linux
package.It is a standard package provided by the kernel developers, allows for more customization than
run-one
and is still very simple.A simple solution from bash-hackers.org that worked for me was using mkdir. This is an easy way how to make sure that only one instance of your program is running. Create a directory with mkdir .lock which returns
So this simple function did all the file locking logic:
This solution is for a bash script that needs to check itself