How to setup cron in Linux?

linux without background image

Linux allows user for scheduling future jobs or CRON. Jobs can be scheduled to run only once in the future or repetitively at fix time.

While working as a system administrator it is fairly regular to perform certain tasks like taking backup, rotating log files and other tasks. To perform these repetitive tasks Linux has Cron and AT.

AT

To run task only once in future at specified time.

# at 09:30
at> echo "hello World" > /dev/tty4
at> Ctrl+d
# atq
# at -c 1
# atrm 1 

CRONTAB

To run task repetitively in future at specified time. In order for cron jobs to execute, crond daemon must be running.

Every user on Linux machine can have jobs scheduled to run at fixed times. This scheduled jobs are stored in separate files for each user in /var/spool/cron/directory. Users can set their scheduled jobs with crontab command.

Time for the execution of cron job is given in a specific order.

*  *  *  *  *
|  |  |  |  |
|  |  |  |  --- Day of week (0-7)(SUN=0,7)
|  |  |  ------ Month (1-12) (Jan, Feb, Mar, ...)
|  |  --------- Day of month (1-31)
|  ------------ Hour (0-23)
--------------- Minute (0-59)

Some examples of the time format are given below.

*     *      *   *  *		Every minute
1     12     *   *  *		At 12:01
5,30  14,20  *   *  *		At 14:05, 14:30, 20:05, 20:30
*/10  17     13  *  *		Every 13th at 17:00, 17:10, 17:20, 17:30, 17:40, 17:50
*/20  14     19  5  *		On May 19 at 14:00, 14:20, 14:40
50    */6    25  9  *		On Sep 25 at 00:50, 06:50, 12:50, 18:50
23    12     15  5  4,6		On May 15 at 12:23 if day is Thu and Sat  

Every user can set their own cron jobs. An administrator user is allowed to set cron jobs for any user.

$ crontab -e
23  12  *  *  *  echo "Student user cron"
ESC:wq
$ crontab -l
$ crontab -r
# crontab -eu student
*/30  11,15  *  *  *  /home/student/backup.sh
ESC:wq
# crontab -lu student
# ls /var/spool/cron 

It is possible to restrict a user from using cron service by writing an entry in /etc/cron.deny

# vim /etc/cron.deny
student
ESC:wq
#