- 08 Feb 2023
- 1 Minute to read
- Print
- DarkLight
Use of Crontab and some examples
- Updated on 08 Feb 2023
- 1 Minute to read
- Print
- DarkLight
Cron is a time based job scheduler in Unix/Linux computer operating systems. A Cron is set up 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 of crontab fields and allowed values for each field:
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
Below we have included a few crontab examples for reference:
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 examples, you will see ">/dev/null 2>&1" at the end of the crontab. To understand this in detail let's looks at the two major parts.
1. /dev/null, 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. These can be called by name, or by number. The "&" sign in front of "1" is standard syntax for file descriptor destination.
In the above examples >/dev/null 2>&1 redirects the standard output to /dev/null to discard all standard output, and then 2 is treated as 1 which is standard output. This means all error, warning or debug messages are discarded. In other words, the cron job will execute without any notification, whether or not it is completed successfully or has failed.
So if you want to receive an email notification to know the status of a cron job failure , 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 the email address specified in crontab.