What is Cron?
Cron is a software utility in Unix based systems, which helps to schedule repetitive tasks. It helps the software developers and system administrators to do some tasks at predefined time intervals. Tasks ranging from Batch Processing, Mass Email Sending, Downloading, Antivirus Scanning… to just pinging your website.
For Windows based systems, the closest option is Windows Task Scheduler.
Most often Cron is used by web developers to generate reports or send emails. Since it repeats, so it is best used for repetitive tasks to be run at specific intervals.
You can schedule your cron jobs to be run every minute, every hour, every day or every week.
To schedule your job, you need to add a command to a text file usually located in /etc, named as crontab.
Each line of a crontab acts as a command. The commands will look something like below:
# ┌───────────── minute (0 - 59) # │ ┌───────────── hour (0 - 23) # │ │ ┌───────────── day of month (1 - 31) # │ │ │ ┌───────────── month (1 - 12) # │ │ │ │ ┌───────────── day of week (0 - 6) (Sunday to Saturday; # │ │ │ │ │ 7 is also Sunday on some systems) # │ │ │ │ │ # │ │ │ │ │ # * * * * * command to execute
# at the beginning denotes commented line.
Your command can be to execute a shell command or to run a PHP script. I will create another post to show how to create a cron job to run PHP scripts.
If you want to verify that your cron is executing at the time that you set, then the cron logs comes handy. On a default installation they can be found at:
Since the file will contain all logs, you can filter the results using grep to show only cron related logs
grep CRON /var/log/syslog
Creating your own Custom Log File
If your scripts outputs something, using print or echo.. etc.. You may want to capture the output of your cron at some particular file. You can use
Here is a custom command to execute a php script every 5 minutes and output the logs to a specific log file
*/5 * * * * /usr/local/bin/php /home/user/public_html/cron-reporting/daily.php >> /home/user/public_html/cron-reporting/logs.txt