Cron is a time-based scheduling service in Linux / Unix-like operating systems. Cron job are used to schedule commands to be executed periodically. You can setup commands or scripts, which will repeatedly run at a set time. Cron is one of the most useful tool in Linux or UNIX like operating systems. The cron service (daemon) runs in the background and constantly checks the /etc/crontab file, /etc/cron./* directories. It also checks the /var/spool/cron/ directory.
In this article I will show you how to execute PHP script in cron job.
Create a PHP Script
First of all create a php script like below.
# cd /var/www/web # vim test.php
Save and close file.
Configure Corn Task
In the following example, the crontab command shown below will activate the cron tasks automatically every five minutes:
*/5 * * * * /usr/bin/php /opt/test.php
In the above sample, the */5 * * * * represents when the task should happen. The first figure represents minutes – in this case, on every “five” minute. The other figures represent, respectively, hour, day, month and day of the week.
* is a wildcard, meaning “every time”.
Find PHP Library
Type the below command to find the php library.
# whereis php
You will get some output like below:
php: /usr/bin/php /etc/php.ini /etc/php.d /usr/lib64/php /usr/include/php /usr/share/php /usr/share/man/man1/php.1.gz
Specify correctly the full path in your command.
Now type the below command to scheduled task and set cron like below.
# crontab -e */5 * * * * /usr/bin/php /opt/test.php
Now type wq! to save it.