How to run a single PHP instance using CRON?

I am 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 crontab , which checks that the PHP instance script is not already running before the PHP instance is called.

crontab -e entry:

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

./start

 #!/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 does not seem to work, and I cannot get any errors to log in to find out how to debug them.

+4
source share
2 answers

You can use lockrun for this: 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`); 
+1
source

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

In bash I recommend you use this:

 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 

Here are some more examples http://wiki.bash-hackers.org/howto/mutex

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

0
source

Source: https://habr.com/ru/post/1439896/


All Articles