For last few weeks I have been working in a web application, where I’ve to do some automated tasks. This is the first time I learned cron process, wrote php script for the cron process and some basic shell script that runs the php script. So here I’m describing the things I learned.
Summary of the tasks:
- Write a php script
- Test the script
- Confirm only one process of the php script is running
- Set the cron so that the php script will run in every 2 minute
So lets see the flow chart of the task:
Write a php script:
The script is as usual you write for normal web application. Here one thing you’ve to keep in mind that, when you use path, it have to be absolute, not relative. This is true for when you run the script as cron not for your localhost. For example: you have to include the code config.php in the script, so if you write the script
include_once "config.php" //get configuration
It will work when you test the script from shell within the same directory of the file, but this will not work when you run the script from cron process in server. So the modified example would be:
include_once "/var/www/domain/yourprojectpath/config.php" //get configuration
Testing the script
After writing the script just run the script from shell either in your pc or in server to test if everything is working fine or not. If you don’t know how to run php from shell then learn it. Its very easy to run php script from shell. The command is:
php cronscript.php
Confirm only one process of the php script is running
To do this there is a shell script using that I run the php script.
#!/bin/sh
#author:mahmud ahsan
#shell script that will run php script
#cronphp.php
if ps -ef | grep -v grep | grep cronphp.php ; then
echo 'Cron already running'
exit 0
else
echo 'Run Cron'
php cronphp.php #if you run the script from shell within the same file directory
php /var/www/domain/yourprojectpath/cronscript.php # when you set the script as cron
exit 0
fi
So set this script as a cron process. Now when this scripts run by cron, it will check if the php script as a process already running or not. If running it exists otherwise it run the php script. Keep in mind that when you set this as a cron process, you definitely provide the absolute path of the php script. Otherwise it will not work.
Set the cron so that the php script will run in every 2 minute
There is a very good tutorial to learn about basics of cron and how to set it. Just follow the tutorial
![]()









good job !
Thank you for sharing, good staring
Waw..nice article,very helped for person like me:) Thanks for share this
Great Job,Dude:)
its nice 1……