I've tried this solution to prevent duplicate cronjob from running.
30,31 12 * * * /usr/bin/flock -n /tmp/my.lockfile ~/Desktop/test.sh >> ~/Desktop/test.log 2>&1
and script test.sh
has
#!/bin/bash
for i in {1..40};do
echo "hello$i"
sleep 2
done
Script test.sh
successfully prevented from running at 12:31 but it stops and I want to resume it. How can I make it only suspend, not stopped and resume back? Is it possible?
You can add a test, in the beginning of the script, to check whether there are another early started instances of the script and while this is true the current instance will sleep. Something like that:
Where:
the variable
$0
contains the script name (and execution path);the variable
$$
contains the PID of the current running instance of the script;ps aux
- output the current processes;grep -v 'grep'
- preserve the lines that containsgrep
within the output of the previous command;grep "$0"
- output only the lines that are related to the current script name;sed -e "/$$/p" -e "/$$/,$ d"
- remove the newer instances of the script; remove all lines after the line that contains the PID of the current instance;grep -vq "$$"
- this is the actual test-q
that will return0
(true - there is at least one older instance of the script) or1
(false - apparently this is the newest existing instance of the script) when the line with PID of the current instance is removed-v
.Here is a complete example:
Here is the test I've made:
In addition you can create a launcher script that will execute your actual script in the above manner.
Read also: