0

How do I avoid cronjob from executing multiple times on the same command? I had tried to look around and try to check and kill in processes but it doesn't work with the below code. With the below code it keeps entering into else condition where it suppose to be "running". Any idea which part I did it wrongly?

#!/bin/sh
devPath=`ps aux | grep "[i]mport_shell_script"` | xargs
if [ ! -z "$devPath" -a "$devPath" != " " ]; then
        echo "running"
        exit
else
        while true
        do
            sudo /usr/bin/php /var/www/html/xxx/import_from_datafile.php /dev/null 2>&1
            sleep 5
        done
fi
exit

cronjob:

*/2 * * * * root /bin/sh /var/www/html/xxx/import_shell_script.sh /dev/null 2>&1
Eric T
  • 1,026
  • 3
  • 20
  • 42

2 Answers2

3

I don't see the point to add a cron job which then starts a loop that runs a job. Either use cron to run the job every minute or use a daemon script to make sure your service is started and is kept running.

To check whether your script is already running, you can use a lock directory (unless your daemon framework already does that for you):

LOCK=/tmp/script.lock # You may want a better name here
mkdir $LOCK || exit 1 # Exit with error if script is already running

trap "rmdir $LOCK" EXIT # Remove the lock when the script terminates

...normal code...

If your OS supports it, then /var/lock/script might be a better path.

Your next question is probably how to write a daemon. To answer that, I need to know what kind of Linux you're using and whether you have things like systemd, daemonize, etc.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
1

check the presence of a file at the beginning of your script ( for example /tmp/runonce-import_shell_script ). If it exists, that means the same script is already running (or the previous one halted with an error).

You can also add a timestamp in that file so you can check since when the script was running (and maybe decide to run it again after 24h even if the file is present)

Asenar
  • 6,732
  • 3
  • 36
  • 49