Crontab

From SaruWiki
Jump to navigation Jump to search

Linux has it's own scheduler, named cron (derived from Greek chronos (χρόνος), meaning time). The Debian package contains the version written by Paul Vixie.

Cron operates by having a daemon crond running in the background, that checks once every minute to see if there are scheduled tasks to run. Tasks can be scheduled by each user by making entries in a file named a crontab. Each user has his own crontab, that cron saves in /var/spool/cron/crontabs/<username>. Furthermore, there's a general crontab in /etc, aptly named crontab. This crontab under Debian has 3 default entries:

# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# m h dom mon dow user  command
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly ) 
#

You can schedule a repetitive task directly in the three cron.* folders; it will get run as user root. To this end, place a suitable script in the folder that matches your need (daily, weekly or monthly). Note, that the script must be named according to the strict rules that run-parts uses: according to the man page, "the names must consist entirely of upper and lower case letters, digits, underscores, and hyphens"'. This means no dot, so do not create a script backup.sh, because it will not get executed.

You can also schedule a task to run as a particular user by adding a line to the /etc/crontab file, specifying the date-and-time pattern, as well as the user under which the script must run.

To see the current user's crontab

>crontab -l

To see a different user's crontab (works only when you're root)

>crontab -u 'username' -l

To edit the current users crontab

>crontab -e

Now you can schedule your task

# +---------------- minute (0 - 59)
# |  +------------- hour (0 - 23)
# |  |  +---------- day of month (1 - 31)
# |  |  |  +------- month (1 - 12)
# |  |  |  |  +---- day of week (0 - 6) (Sunday=0 or 7)
# |  |  |  |  |
  *  *  *  *  *  command to be executed (full path to command/script)