3

I'm having trouble running a single instance of a PHP script using CRON. Perhaps someone can help explain what is needed. Currenty, I have a startup script that is called by crontab which checks to make sure an instance of a PHP script isn't already running before calling the PHP instance.

crontab -e entry:

* * * * * /var/www/private/script.php >> /var/www/private/script.log 2>&1 &

./startup

#!/bin/bash

if ps -ef | grep '[s]cript';
        then
                exit;
        else
                /usr/bin/php /var/www/private/script.php  >>/var/www/private/script.log 2>&1 &
                echo 'started'
fi

This doesn't seem to be working and I can't seem to get any errors logged to know how to proceed to debug this.

Xeoncross
  • 55,620
  • 80
  • 262
  • 364
  • Have you tried running `/usr/bin/nohup php /var/www/private/script.php >>/var/www/private/script.log 2>&1 &` in terminal directly? – s.webbandit Oct 15 '12 at 19:56

2 Answers2

1

You can use lockrun for that: http://www.unixwiz.net/tools/lockrun.html

* * * * * /usr/local/bin/lockrun --lockfile=/var/run/script.lockrun -- php /home/script.php

Or use Perl:

system('php /home/script.php') if ( ! `ps -aef|grep -v grep|grep script.php`);
Green Black
  • 5,037
  • 1
  • 17
  • 29
0

Testing processes is not the most reliable way to prevent multiple instance of a script.

In bash, I recommend you to use that :

if ( set -o noclobber; echo "locked" > "$lockfile") 2> /dev/null; then
  trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT
  echo "Locking succeeded" >&2
  rm -f "$lockfile"
else
  echo "Lock failed - exit" >&2
  exit 1
fi

There's another examples in this page http://wiki.bash-hackers.org/howto/mutex

Another solution (if not using NFS) is to use flock (1), see How do I use the linux flock command to prevent another root process from deleting a file?

Community
  • 1
  • 1
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223