Last updated on April 6th, 2017 at 12:32 pm
In this post i will explain you how to run PHP file every 5 second in background using Shell script and Cron job. If you have your own VPS you can test it. There are lots of information about Bash script and Cron job on web so i am not going to copy that. Without wasting any time we create our script and run follow below step to start creating script.
Step 1. Login to your VPS using terminal or putty.
Step 2. After logged successfully go to location where you want to create PHP file and create file and open file using terminal as shown below
cd /var/www/html/ nano script.php
i am using nano editor for editing file, now paste below code you want to execute for this sample i put text in it.
<?php echo "I am running"; ?>
after this we need to set permission for this file to execute properly
chmod +x script.php
Step 3. Now we can create our Bash script file to run script.php file after 5 sec interval
create new bash file using nano editor
nano script.sh
and after that paste bellow code
#!/bin/bash while true; do begin=`date +%s` php /var/www/html/script.php end=`date +%s` if [ $(($end - $begin)) -lt 5 ]; then sleep $(($begin + 5 - $end)) fi done
Now check your script file if its executable or not using below command
ls -la script.sh
if its show white color its mean this file is not executable you need to change permission for this file using below command
chmod +x script.sh
Now rerun above command to check if its turn to green its mean it is executable.
Now run this Bash file using this command
./script.sh
If you did not miss any step your script start running.
Step 4. Now we need to run this Bash script using cron so it start automatically and complete our task. To setup cron job you need to run below command in terminal
crontab -e
Now at the end of file add below command to run Bash file
* * * * * /var/www/html/script.sh >> /var/www/html/log
I am creating log file so whenever this cron run it enter output to log file. Save your file and that’s it. Hope this help you. 🙂