Cron jobs are useful when you want to execute some code to be executed on specified time or date like once in seven day or once in a day. Sometimes you will need to run Cron job to do particular task like send mails to registered users on each Sunday. Cron job is a Linux command for scheduling a task to be executed sometimes in the future. There are many situations when a web application may need certain task to run periodically. In this Article, we are going to tell you a lot about the Cron jobs. Here we will run PHP file by writing a Cron job will execute that file once in a week at 12:10 PM.The syntax of writing Cron job is as follows:
* * * * * php /var/www/html/folder_name/file_name.php -- In case of Apache Web Server
* * * * * php /srv/www/html/folder_name/file_name.php -- In case of Ngnix Web Server
As shown above first * for minute, second for Hour, third for which day of month, four for which month to be executed and fifth for which day of week.
To run Cron job we should know basic command like list of all scheduled jobs and edit these jobs and create new jobs as follows:
To see list of scheduled Cron jobs type following command in command line or terminal as shown below. Here we are using Putty which is terminal emulator, serial console and network file transfer application.
crontab -l
After writing following command press enter will show all scheduled Cron job or tasks.
To edit or create new Cron job type following command as shown below. Now you can edit or create new jobs or task.
crontab –e
After writing following command press enter can edit or create new Cron Job. Below we will create new job to run mail.php file.
To stop any Cron job add # sign in front of command as shown below as follows:
#* * * * * php /var/www/html/folder_name/file_name
Here # sign works as comment and will stop to execution php file.
Mail to user once in a week:
[php]
[/php]
Upload this file on server and save it any folder .In my case I created cron folder and saved mail.php file in cron folder.
10 12 * * 6 php /var/www/html/cron/mail.php
After writing following command press Ctrl+X then it will ask you for saving following command. Type y for saving then press enter will save following Cron job and it will run on each Saturday at 12:10 PM.
Here we are giving other commands to run according to your need as follows:
* * * * * php /var/www/html/folder_name/file_name.php
0 * * * * php /var/www/html/folder_name/file_name.php
15 * * * * * php /var/www/html/folder_name/file_name.php
30 2 * * * php /var/www/html/folder_name/file_name.php
We hope you have understood to run Cron job still have any confusion or query feel free to comment below