Linux crontab tutorial with Examples

If you already have some experience as a Linux system administrator, chances are you know what cron is and what it does. If you’re just starting working with Linux, it’s essential knowledge that will certainly serve you later. Either way, if you already have the knowledge, this article will refresh it. If not, you will get a guide to start you up. So you’re only expected to have some basic knowledge of Linux systems and, as usual, a desire to learn.

Cron’s name comes from Chronos, the Greek personification of time. And it’s a very inspired choice, because cron helps you schedule different tasks you want your system to perform at given times. If you used Windows systems, chances are you stumbled across the Scheduled Tasks tool. Generally speaking, the purpose is the same, the differences are…well, too many to name here.

The idea is cron is more flexible and appropriate for serious system management tasks. If you need some example use cases, just think about backups: do you want to perform backup tasks when you’re responsible for hundreds of machines? We thought not. You just write a simple Bash script using rsync, for example, schedule it to run, say, daily and forget about it. All you have to do now is check the logs from time to time. We even know people that use cron to remind them of important personal events, like birthdays.

But cron is just a daemon running the tasks you tell it to run. Is there a tool to help us edit/add/remove those tasks? Of course, and it’s called crontab (the name comes from cron table). But let us start with the beginning. Read on to learn how to use cron.

In this tutorial you will learn:

  • Is it necessary to install cron on Linux?
  • How to cron to schedule tasks
  • Multiple crontab examples for yearly, monthly, daily tasks etc.
  • How to use cron files within the /etc/ directory
Linux crontab tutorial with Examples
Linux crontab tutorial with Examples
Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any Linux system
Software Cron
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

Do I need to install cron?




Most of the Linux distributions out there use Vixie Cron or some derivative (Fedora) as the default cron implementation, and that’s what we shall use in this article. Also, most distributions come with cron already installed, since it’s a very important part of any Linux system. Although you, if a desktop user, might not ever need to use it directly, your system or some installed applications might (the periodical update of the manpages database is a good example).

So basically there’s not so much we can write in this section, because most of the distributions we know include cron in the base system. A notable exception is Gentoo, where you have to install vixie-cron by hand and add it to the default runlevel. Arch, Debian and Slackware, also all Ubuntu versions, Fedora and OpenSUSE all have cron installed in base and set up to start at boot. We suggest (strongly, as a matter of fact) you read the cron and crontab manual pages, since lots of Linux distributions patch their software in order to fit better with the rest of the system.

So there are chances one feature you’ll find on Gentoo, for example, won’t be available on Slackware. And anyway, nothing compares to reading the manual, especially when dealing with a new piece of software you’re going to use quite often.

How to use cron

Now, let’s put cron to work. What we first have to think about is what command do we need to run. Does it require root privileges or not? Let’s presume for now that we will use crontab to add a simple script to execute every five minutes, as our normal user.

Cron example

Let’s write a simple script that will exhibit a simple curses-based dialog box in a terminal (requires dialog and some terminal emulator – we will use xterm here):

#!/bin/sh
xterm -e "dialog --msgbox 'Testing cron...' 234 234"
# This is a very simple example, treat it as it is

Name the file crontest.sh and make it executable, since everything that will be executed by cron must be executable.

$ chmod +x crontest.sh 

And now we must edit our user’s crontab in order to add an entry for our marvelous script :

$ crontab -e

-e stands for edit, and -r stands for remove.

WARNING
Be very careful! Many sysadmins, out of fatigue or carelessness, typed -r instead of -e, since the keys are right next to each other, and removed all their crontab entries.

Anyway, you will most likely see a commented file (crontab uses #’s for comments) that gives you examples and explains what every field does. Yes, a crontab entry is made of fields, with the last one specifying the command to be executed and the rest being time-specific entries, as we will see.

Now, our entry in crontab for our script to be executed every five minutes is:

*/5 * * * * export DISPLAY=:0 && /home/$user/crontest.sh 

We need to export the DISPLAY variable for xterm not to mail us with “DISPLAY is not set” errors. Now, let’s see what each field does.

Crontab fields




If you ever used wildcards, then you’ll be familiar with the asterisks in crontab: they mean “match all values”. The fields in a default Linux crontab (watch out, some other Unix systems might have different cron implementations) mean, from left to right: minute, hour, day of the month, month, day of week, year (not mandatory) and command, respectively.

So if we wanted to run our script every time at five minutes past every hour, every day, every month and every year, we would have just done so:

5 * * * *  export DISPLAY=:0 && /home/$user/crontest.sh
Configuring a crontab entry on Linux
Configuring a crontab entry on Linux

We urge you to be careful about the day of the week field: maybe in your country the first day of the week is Monday, but there are other cultures that have the first day of the week set as Sunday. There are cultural and religious differences you have to take care of if working in multinational, multicultural environments.

Cron sends notifications to the user owning the job by e-mail by default ($user@$hostname). If you want to change the address, just use MAILTO=$email_address in your crontab. If you want to disable this, put >/dev/null 2>&1 at the end of your entry.

Now, if you’re already sick and tired of that popup window coming up every five minutes, use crontab -e again to delete it, or, simpler, comment it out. If you want to see what is in your crontab, just use the -l (list) option. We invite you to play around, create new entries and see if they work as you expected.

Cron files inside the /etc directory

What we did before was just something trivial and potentially funny in order to get you started. From now on we will assume you have some serious business to take care of and go in that direction. The subtitle above refers to directories in /etc that take care of periodic system maintenance tasks.

For example, since we referred to that earlier, our /etc/cron.weekly contains a script called man-db which updates the manual pages database. These are scripts that come with your distribution and are run according to the /etc/crontab file.

Since the best way of learning is by doing some research, take your time to look through this file yourself. You will see similar entries to what you read before, only the commands to execute will differ. run-parts is a small utility designed to run all scripts in a given folder, which are the scripts in cron.{hourly,daily,weekly,monthly}. Make sure you understand when they are set to run and why are these hours/days chosen the way they are.

The attentive reader might have noticed that there is a field in /etc/crontab that wasn’t present when editing his/her crontab: a user field. The explanation is simple and the reason is security. If you invoke crontab -e as $user, it’s certain that any command scheduled will be run as $user.

But since /etc/crontab is system-wide, there appears a need to specify the user, since there might be certain scripts or applications that will have to run as another user, not root that is, especially if the sysadmin is security-conscious and adds users and groups to the system as need arises.

An example: for backups you will not need the full power of the root user, only the necessary rights to read and write specific locations (there’s more to it, but let’s keep it simple). So, the administrator creates a backups group and a backupadmin user, with the necessary rights, and executes the nightly backup scripts via cron like so:

30 23 * * * backupadmin /home/backupadmin/nightlybkup.sh 

This will execute the script specified in the last field every night at 23:30. Now, if we’d want backups to be executed only Monday to Friday, we would have done this:



30 23 * * 1-5 backupadmin /home/backupadmin/nightlybkup.sh 

If you only want backups at night, but only Mondays, Wednesdays and Fridays, replace 1-5 with 1,3,5. Once you get your feet wet and know exactly what you need, cron will become easy to use and easy to understand.

Security considerations

There are a lot of situations in which you don’t want to allow every user that has access to your system to create crontab entries. This is where /etc/cron.deny and /etc/cron.allow come into play. Their usage is basically the same as /etc/hosts.allow and /etc/hosts.deny, so if you used these files in the past you’ll feel right at home. These two files (cron.deny and cron.allow) don’t exist by default, at least on the systems we work with, so the default behavior is to allow everyone to have their crontab entries. You can check what cron-related files you have in /etc with

$ ls /etc | grep cron

Again, this is only on Linux, since the lack of these files on Solaris systems mean exactly the opposite, plus the files have different locations. cron.allow is checked first, so we usually enter ALL in cron.deny then enter only the users we want to give access to in cron.allow.

Cron Scheduler Examples

In order to get familiar with the crontab syntax, which is a little confusing at first, we’ve compiled a list of various examples that will schedule tasks for all sorts of different times and frequencies.

  1. Run a script every minute:
    * * * * * /usr/local/bin/check-disk-space.sh
    

    This command will be executed every minute, day and month.

  2. This command will execute the checkdrive.sh script at 02:30 every 10th of January, June and December.
    30 02 10 01,06,12 * /home/$user/bin/checkdrive.sh
    
  3. Run the script ever half hour:
    00,30 * * * * /home/$user/backupdata.sh
    
  4. Run on weekends only:


    * * * * 6,7 /usr/bin/weekend
    
  5. Run twice a day. This will run daily on 11:20 and 16:20.
    20 11,16 * * * /usr/sbin/command
    
  6. This will run hourly every 2nd of May.
    01 * 2 05 * /sbin/system_command
    
  7. The below command will run Monday-Friday every 10 minutes.
    */10 * * * 1-5 /usr/local/bin/check-disk-space.sh
    
  8. This command will be executed once during working hours and working days.
    00 09-17 * * 1-5 /usr/local/bin/check-disk-space.sh
    
  9. This command will be executed only once a year, midnight, Jan. 1st
    0 0 1 1 * /usr/local/bin/check-disk-space.sh
    
  10. This command will be executed twice a year ( every 6 months ) at 12AM and 12PM.
    0 0,12 1 */6 * /usr/local/bin/check-disk-space.sh
    
  11. This command will be executed every 3th Thursday in any given month at 10AM.
    0 10 15-21 * 4 /usr/local/bin/check-disk-space.sh
    
  12. This command will be executed every day 20 minutes after every even hour (0:20, 2:20…22:20).
    20 0-23/2 * * * /usr/local/bin/check-disk-space.sh
    

Closing Thoughts




Even though you might find cron entries a little daunting at first, after a short while you will remember the order and meaning of the fields and, since now you know where are the files to edit, scheduling using cron will become a breeze. All it will take is a little practice.



Comments and Discussions
Linux Forum