CRON job still running?

Hi All,

I am writing a script that will eventually be executed by a cron job every 15 minutes. I want to make sure that my logic/script doesn't get executed if a previous job is still running. What would be the best way to handle that scenario? I was thinking to make my script create a temporary file once it starts and then remove it at the very end before exit. In this case I can always check if that temp file exist which will mean that the script is still running.
Is there a more elegant way to do this?

Thanks

I'd rather write the PID of your cronscript to that tempfile, so you can check right away if the process is still running or not, by matching ps $(cat tempfile) .

So in your cron script you do something like:

doit=false
[[ ! -f tempfile ]] && doit=true
[[ -f tempfile ]] && [[ ! $(ps $(cat tempfile) ]] && doit=true

if [[ $doit ]];then
      echo $$ > tempfile

      echo "your code"

      rm -f tempfile
fi

Hope this helps

NOTE: For cron scripts you need to write full paths to commands, not like this example!

1 Like