Use of Crontab, and some examples

Follow

Cron is a time based job scheduler in Unix/Linux computer operating systems. A Cron is setup to schedule jobs, mostly commands or scripts to run periodically at fixed times, dates, or intervals. So basically it automates system maintenance or administration. 

Linux Crontab Format is as follows.

------------------------
MIN HOUR DOM MON DOW CMD
------------------------

Here is a brief explanation on crontab fields and allowed values for each fields.

MIN     Minute field     0 to 59
HOUR     Hour field     0 to 23
DOM     Day of Month     1-31
MON     Month field     1-12
DOW     Day Of Week     0-6
CMD     Command     Any command to be executed

Here are few crontab examples.


1. Cron to run once every Hour

------------------------
0 * * * * /usr/bin/php /home/username/public_html/cron.php >/dev/null 2>&1
------------------------

2. Once every 15 minutes, every 3rd hour

------------------------
*/15 */3 * * * /usr/bin/php /home/username/public_html/cron.php >/dev/null 2>&1
------------------------

3. Once every Day at 14:23

------------------------
23 14 * * * /usr/bin/php /home/username/public_html/cron.php >/dev/null 2>&1
------------------------

4. Once Weekly, every Monday at 14:23

------------------------
23 14 * * 1 /usr/bin/php /home/username/public_html/cron.php >/dev/null 2>&1
------------------------

5. Once Every Month, On the 4th, at 14:23

------------------------
23 14 4 * * /usr/bin/php /home/username/public_html/cron.php >/dev/null 2>&1
------------------------

 

In the above example, you will see ">/dev/null 2>&1" within the end of the crontab. To understand this in detail lets looks at the two major parts.

1. /dev/null, it is a special device file that discards all data written to it without error.

2. The file descriptors, they are usually called STDIN, STDOUT and STDERR, and numbered as 0, 1, and 2 respectively, they can be called by name, or by number. The "&" sign in front of "1" is standard syntax for file descriptor destination.

Here  the “>/dev/null 2>&1″ redirects the standard output to /dev/null to discard all standard output, and then 2 is been treated as 1 which is standard output, it means all error, warning or debug messages are discarded. In other words, the cron job will execute without any notification, whether or not it’s completed successfully or failed. 

So if you want to receive email notification to know the status of a cron job failed to run properly, just use “>/dev/null” instead of “>/dev/null 2>&1", “>/dev/null” will only ignore standard output, but will send all warning, debug, error and any other exception messages to email address specified in crontab.

Have more questions? Submit a request

Comments

Powered by Zendesk