Reputation: 57184
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.
Upvotes: 3
Views: 1268
Reputation: 185063
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?
Upvotes: 0
Reputation: 5084
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`);
Upvotes: 1