Linux Cron Jobs

The Linux Cron utility allows for automation and is used to schedule tasks such as scripts or commands that you want executed at certain times or at repeated times, such as every hour.

Cron’s settings are in a specific file called crontab (cron table) and the cron service checks the /etc/crontab file, /etc/cron.* directories. Each line of a crontab file represents a job and is composed of a CRON expression, followed by a shell command to execute.

Cron Definition Table:

* * * * *                 command to be executed
┬ ┬ ┬ ┬ ┬
│ │ │ │ │
│ │ │ │ │
│ │ │ │ └───── day of week (0 – 6) (0 to 6 are Sunday to Saturday, or use names)
│ │ │ └────────── month (1 – 12)
│ │ └─────────────── day of month (1 – 31)
│ └──────────────────── hour (0 – 23)
└───────────────────────── min (0 – 59)

Example of a Cron Job:

 30 3 * * 1 sh /home/keith/scripts/myscript.sh 

As you can see this will run a script located in /home/keith/scripts named myscript.sh and is set to run every Monday morning at 3:30am.

To list cron jobs:

 crontab -l 

To edit or create a cron job:

 crontab -e 

There is also Anacron, which can be confusing for people new to Linux. Think of Anacron as a system cron or jobs handled and looked after by the operating system. Anacron assumes that the system is not running all the time, and will run jobs if they did not run due the the system being turned off.

Easter Eggs!

Crontab has some very cool additions that not many people know about, I call them crontab easter eggs!

 @hourly /home/keith/scripts/backup.sh 

The above will run the backup script every hour by using the @hourly entry! There are some others like:

 @midnight, @daily, @monthly, @annually and @reboot 

@reboot runs once when the system first boots and/or on reboots, so you can use it instead of the rc.local file.

Reference:
man cron
WikiPedia: http://en.wikipedia.org/wiki/Cron

Bookmark the permalink.