0

I have a php script that I call via cron per minute. but I don't want it running again while the first call is still loading or in progress?

I have tried using MYSQL but my problem sometimes, the script did not finish loading so it cannot update the MYSQL that the script is finished. it will stuck in loading.

Thank you

Milan
  • 631
  • 1
  • 5
  • 21
Howard L
  • 3
  • 3

1 Answers1

0

You have to use a lockfile or check if it is already running before starting the new one.

See How to prevent PHP script running more than once?

I have taken the solution there and modified it somewhat:

#!/bin/bash

#change to the name of php-file
SCRIPT='my-php-script.php'

#get running processes containing php-file
PIDS=$(ps aux | grep "$SCRIPT" | grep -v grep)

if [ -z "$PIDS" ]; then
  echo "Starting $SCRIPT ..."
  #change path to script to its real path
  /usr/bin/env php "/path/to/script/$SCRIPT" >> "/var/log/$SCRIPT.log" &
else
  echo "$SCRIPT already running."
fi

You should try to run this on the command line first to see that it works, then add it to cron. Depending on the system it might have some paths that are different and not find parts necessary to run correctly.

Community
  • 1
  • 1
Snorre Løvås
  • 251
  • 1
  • 5
  • Thank you. I use the bash script. – Howard L Jan 10 '16 at 17:08
  • I notice that the script is running but it did not run the php file... on the bash script there a conditional IF... #!/bin/bash PIDS=`ps aux | grep onlytask.php | grep -v grep` if [ -z "$PIDS" ]; then echo "Starting onlytask.php ..." php /usr/local/src/onlytask.php >> /var/log/onlytask.log & else echo "onlytask.php already running." fi – Howard L Jan 12 '16 at 03:56
  • The if statement is be able to skip running your program is already running. The $PIDS variable is empty if it is not running and then -z (is null) will match, and the php file is safe to run. I've updated the answer with a slightly modified version of the script above. – Snorre Løvås Jan 12 '16 at 21:34