Crontab

From Andreida

basics

The commands you put into your crontab will be executed unless you start a line with "#". If the command has any output and you have set the variable MAILTO before that line, the output of the command will be sent to you.

You can have as many MAILTO lines as you wish, the last before your cronjob line will be used. So every cronjob can send mail to another mail address or - if MAILTO has been set to nothing (MAILTO=) - no mail will be sent at all.

When cron is being executed, often no PATH has been set. So you can often make it work with something like

33 16 3 * * . /etc/profile && php /root/scripts/myScript-0815.php

commands

  • list the cron jobs of the current user
crontab -l 
  • edit/create cron jobs
crontab -e

If you do not get vim as editor for your cronjobs, you can set it with the environment variable "VISUAL". Find out what is the path to vim on your system:

which vim

Then put this into your ~/.bashrc:

export VISUAL=/usr/bin/vim

then reload/source the .bashrc with

. ~/.bashrc

Do not forget the "." in front.

schedules

The following will clear the Apache error log at one minute past midnight (00:01 of every day of the month, of every day of the week).

1 0 * * *  echo -n "" > /www/apache/logs/error_log

The following will run the script /home/user/test.pl every 5 minutes.

*/5 * * * *  /home/user/test.pl


SHELL=/bin/bash
PATH=/sbin:/bin/:/usr/sbin/:/usr/bin
MAILTO=root
HOME=/
.---------------- minute (0 - 59) 
|  .------------- hour (0 - 23)
|  |  .---------- day of month (1 - 31)
|  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ... 
|  |  |  |  .---- day of week (0 - 7) (Sunday=0 or 7)  OR sun,mon,tue,wed,thu,fri,sat 
|  |  |  |  |
*  *  *  *  *  command to be executed
  • for numerics:
    • lists 2,4,7
    • ranges 2-5
    • combination of list and range 2-4,6,8-11
  • if "day of month" and "day of week" are both not "*", then they both are used, they do not restrict each other anymore
  • steps after an asterix: */2 every 2 whatever