Php – run multiple instance of same php script from bash

bashcronPHP

I am running a cron job to execute a php file multiple times per minute like this

*  *  *  *  * /usr/bin/php /var/www/html/myFile.php >> /var/www/html/cronlog 2> /dev/null
*  *  *  *  * sleep 10; /usr/bin/php /var/www/html/myFile.php >> /var/www/html/cronlog 2> /dev/null
*  *  *  *  * sleep 20; /usr/bin/php /var/www/html/myFile.php >> /var/www/html/cronlog 2> /dev/null
*  *  *  *  * sleep 30; /usr/bin/php /var/www/html/myFile.php >> /var/www/html/cronlog 2> /dev/null
*  *  *  *  * sleep 40; /usr/bin/php /var/www/html/myFile.php >> /var/www/html/cronlog 2> /dev/null
*  *  *  *  * sleep 50; /usr/bin/php /var/www/html/myFile.php >> /var/www/html/cronlog 2> /dev/null

This executes myFile.php fine but when i count the number of process running
ps -ef | grep php | wc -l
It adds up and cpu usage hits 100%!

Should i be running a single bash file and from within the bash file run multiple php files staggered?

If so how would I write the bash script?

#!/bin/bash
????
????
????

edit: I would like to mention that the execution of the file should take place after the previous execution is complete.

Also a cron job is not mandatory as krisFR has pointed out

Best Answer

I don't know what your script is actually doing, maybe it requires a lot of server resources, and for sure the next one is starting before the previous one has finished. Is it what you want ? I will guess "no".

I would suggest to run a single Bash script, something like :

#!/bin/bash
while true; do
   /usr/bin/php /var/www/html/myFile.php >> /var/www/html/cronlog 2> /dev/null
   sleep 10
done

Let's consider you put the above code in file /home/me/myscript.sh you can run it in background using :

nohup /home/me/myscript.sh &

Test and check if it feets your need.

Related Topic