linux crontab

32
Linux Crontab: 15 Awesome Cron Job Examples An experienced Linux sysadmin knows the importance of running the routine maintenance jobs in the background automatically. Linux Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis. let us review 15 awesome examples of crontab job scheduling. Linux Crontab Format MIN HOUR DOM MON DOW CMD

Post on 22-Oct-2014

166 views

Category:

Education


2 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Linux crontab

Linux Crontab: 15 Awesome Cron Job Examples

An experienced Linux sysadmin knows the importance of running the routine maintenance jobs in the background automatically.

Linux Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.

let us review 15 awesome examples of crontab job scheduling.

Linux Crontab Format

MIN HOUR DOM MON DOW CMD

Table: Crontab Fields and Allowed Ranges (Linux Crontab Syntax)Field Description Allowed Value

MIN Minute field 0 to 59HOUR Hour field 0 to 23DOM Day of Month 1-31

Page 2: Linux crontab

MON Month field 1-12DOW Day Of Week 0-6CMD Command Any command to be executed.

1. Scheduling a Job For a Specific TimeThe basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.

30 08 10 06 * /home/ramesh/full-backup

30 – 30th Minute 08 – 08 AM 10 – 10th Day 06 – 6th Month (June) * – Every day of the week

2. Schedule a Job For More Than One Instance (e.g. Twice a Day)The following script take a incremental backup twice a day every day.

This example executes the specified incremental backup shell script (incremental-backup) at 11:00 and 16:00 on every day. The comma separated value in a field specifies that the command needs to be executed in all the mentioned time.

00 11,16 * * * /home/ramesh/bin/incremental-backup

Page 3: Linux crontab

00 – 0th Minute (Top of the hour) 11,16 – 11 AM and 4 PM * – Every day * – Every month * – Every day of the week

3. Schedule a Job for Specific Range of Time (e.g. Only on Weekdays)If you wanted a job to be scheduled for every hour with in a specific range of time then use the following.

Cron Job everyday during working hoursThis example checks the status of the database everyday (including weekends) during the working hours 9 a.m – 6 p.m

00 09-18 * * * /home/ramesh/bin/check-db-status

00 – 0th Minute (Top of the hour) 09-18 – 9 am, 10 am,11 am, 12 am, 1 pm, 2 pm, 3 pm, 4

pm, 5 pm, 6 pm * – Every day * – Every month * – Every day of the weekCron Job every weekday during working hoursThis example checks the status of the database every weekday (i.e excluding Sat and Sun) during the working hours 9 a.m – 6 p.m.

00 09-18 * * 1-5 /home/ramesh/bin/check-db-status

Page 4: Linux crontab

00 – 0th Minute (Top of the hour) 09-18 – 9 am, 10 am,11 am, 12 am, 1 pm, 2 pm, 3 pm, 4

pm, 5 pm, 6 pm * – Every day * – Every month 1-5 -Mon, Tue, Wed, Thu and Fri (Every Weekday)

4. How to View Crontab Entries?View Current Logged-In User’s Crontab entriesTo view your crontab entries type crontab -l from your unix account as shown below.

ramesh@dev-db$ crontab -l@yearly /home/ramesh/annual-maintenance*/10 * * * * /home/ramesh/check-disk-space

[Note: This displays crontab of the current logged in user]

View Root Crontab entriesLogin as root user (su – root) and do crontab -l as shown below.

root@dev-db# crontab -l

no crontab for root

Crontab HowTo: View Other Linux User’s Crontabs entriesTo view crontab entries of other Linux users, login to root and use -u {username} -l as shown below.

Page 5: Linux crontab

root@dev-db# crontab -u sathiya -l@monthly /home/sathiya/monthly-backup00 09-18 * * * /home/sathiya/check-db-status

5. How to Edit Crontab Entries?Edit Current Logged-In User’s Crontab entriesTo edit a crontab entries, use crontab -e as shown below. By default this will edit the current logged-in users crontab.

ramesh@dev-db$ crontab -e@yearly /home/ramesh/centos/bin/annual-maintenance*/10 * * * * /home/ramesh/debian/bin/check-disk-space~"/tmp/crontab.XXXXyjWkHw" 2L, 83C

[Note: This will open the crontab file in Vim editor for editing.Please note cron created a temporary /tmp/crontab.XX... ]

When you save the above temporary file with :wq, it will save the crontab and display the following message indicating the crontab is successfully modified.

~

"crontab.XXXXyjWkHw" 2L, 83C written

crontab: installing new crontab

Edit Root Crontab entries

Page 6: Linux crontab

Login as root user (su – root) and do crontab -e as shown below.

root@dev-db# crontab -e

Edit Other Linux User’s Crontab File entriesTo edit crontab entries of other Linux users, login to root and use -u {username} -e as shown below.

root@dev-db# crontab -u sathiya -e@monthly /home/sathiya/fedora/bin/monthly-backup00 09-18 * * * /home/sathiya/ubuntu/bin/check-db-status~~~"/tmp/crontab.XXXXyjWkHw" 2L, 83C

6. Schedule a Job for Every Minute Using Cron.Ideally you may not have a requirement to schedule a job every minute. But understanding this example will will help you understand the other examples mentioned below in this article.

* * * * * CMD

The * means all the possible unit — i.e every minute of every hour through out the year. More than using this * directly, you will find it very useful in the following cases.

Page 7: Linux crontab

When you specify */5 in minute field means every 5 minutes.

When you specify 0-10/2 in minute field mean every 2 minutes in the first 10 minute.

Thus the above convention can be used for all the other 4 fields.

7. Schedule a Background Cron Job For Every 10 Minutes.Use the following, if you want to check the disk space every 10 minutes.

*/10 * * * * /home/ramesh/check-disk-space

It executes the specified command check-disk-space every 10 minutes through out the year. But you may have a requirement of executing the command only during office hours or vice versa. The above examples shows how to do those things.

Instead of specifying values in the 5 fields, we can specify it using a single keyword as mentioned below.

There are special cases in which instead of the above 5 fields you can use @ followed by a keyword — such as reboot, midnight, yearly, hourly.

Table: Cron special keywords and its meaningKeyword Equivalent

@yearly 0 0 1 1 *@daily 0 0 * * *@hourly 0 * * * *

Page 8: Linux crontab

@reboot Run at startup.

8. Schedule a Job For First Minute of Every Year using @yearlyIf you want a job to be executed on the first minute of every year, then you can use the@yearly cron keyword as shown below.

This will execute the system annual maintenance using annual-maintenance shell script at 00:00 on Jan 1st for every year.

@yearly /home/ramesh/red-hat/bin/annual-maintenance

9. Schedule a Cron Job Beginning of Every Month using @monthlyIt is as similar as the @yearly as above. But executes the command monthly once using@monthly cron keyword.

This will execute the shell script tape-backup at 00:00 on 1st of every month.

@monthly /home/ramesh/suse/bin/tape-backup

10. Schedule a Background Job Every Day using @dailyUsing the @daily cron keyword, this will do a daily log file cleanup using cleanup-logs shell scriptat 00:00 on every day.

Page 9: Linux crontab

@daily /home/ramesh/arch-linux/bin/cleanup-logs "day started"

11. How to Execute a Linux Command After Every Reboot using @reboot?Using the @reboot cron keyword, this will execute the specified command once after the machine got booted every time.

@reboot CMD

12. How to Disable/Redirect the Crontab Mail Output using MAIL keyword?By default crontab sends the job output to the user who scheduled the job. If you want to redirect the output to a specific user, add or update the MAIL variable in the crontab as shown below.

ramesh@dev-db$ crontab -l

MAIL="ramesh"

@yearly /home/ramesh/annual-maintenance

*/10 * * * * /home/ramesh/check-disk-space

Page 10: Linux crontab

[Note: Crontab of the current logged in user with MAIL variable]

If you wanted the mail not to be sent to anywhere, i.e to stop the crontab output to be emailed, add or update the MAIL variable in the crontab as shown below.

MAIL=""

13. How to Execute a Linux Cron Jobs Every Second Using Crontab.You cannot schedule a every-second cronjob. Because in cron the minimum unit you can specify is minute. In a typical scenario, there is no reason for most of us to run any job every second in the system.

14. Specify PATH Variable in the CrontabAll the above examples we specified absolute path of the Linux command or the shell-script that needs to be executed.

For example, instead of specifying /home/ramesh/tape-backup, if you want to just specify tape-backup, then add the path /home/ramesh to the PATH variable in the crontab as shown below.

ramesh@dev-db$ crontab -l

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/home/ramesh

Page 11: Linux crontab

@yearly annual-maintenance

*/10 * * * * check-disk-space

[Note: Crontab of the current logged in user with PATH variable]

15. Installing Crontab From a Cron FileInstead of directly editing the crontab file, you can also add all the entries to a cron-file first. Once you have all thoese entries in the file, you can upload or install them to the cron as shown below.

ramesh@dev-db$ crontab -l

no crontab for ramesh

$ cat cron-file.txt

@yearly /home/ramesh/annual-maintenance

*/10 * * * * /home/ramesh/check-disk-space

Page 12: Linux crontab

ramesh@dev-db$ crontab cron-file.txt

ramesh@dev-db$ crontab -l@yearly /home/ramesh/annual-maintenance*/10 * * * * /home/ramesh/check-disk-space

Note: This will install the cron-file.txt to your crontab, which will also remove your old cron entries. So, please be careful while uploading cron entries from a cron-file.txt.

Cron Vs Anacron: How to Setup Anacron on Linux (With an Example)

by SATHIYAMOORTHY  on MAY 10, 2011

Anacron is the cron for desktops and laptops.

Anacron does not expect the system to be running 24 x 7 like a server.

Page 13: Linux crontab

When you want a background job to be executed automatically on a machine that is not running 24 x 7, you should use anacron.

For example, if you have a backup script scheduled everyday at 11 PM as a regular cron job, and if your laptop is not up at 11 PM, your backup job will not be executed.

However, if you have the same job scheduled in anacron, you can be sure that it will be executed once the laptop come back up.

Anacrontab FormatJust like how cron has /etc/crontab, anacron has /etc/anacrontab.

/etc/anacrontab file has the anacron jobs mentioned in the following format.

period delay job-identifier command

Field 1 is Recurrence period: This is a numeric value that specifies the number of days. 1 – daily 7 – weekly 30 – monthly N – This can be any numeric value. N indicates number of

daysNote: You can also use ‘@monthly’ for a job that needs to be executed monthly.

Page 14: Linux crontab

Field 2 is Delay: This indicates the delay in minutes. i.e X number of minutes anacron should wait before executing the job after the the machine starts.Field 3 is Job identifier: It is the name for the job’s timestamp file. It should be unique for each job. This will be available as a file under the /var/spool/anacron directory. This file will contain a single line that indicates the last time when this job was executed.

# ls -1 /var/spool/anacron/

test.daily

cron.daily

cron.monthly

cron.weekly

# cat /var/spool/anacron/test.daily

20110507

Field 4 is command: Command or shell script that needs to be executed.Just like shell scripts, comments inside anacrontab file starts with #

Note: For /etc/crontab file format, refer to our Linux Crontab: 15 Awesome Cron Job Examplesarticle.

Page 15: Linux crontab

Anacron ExampleThe following example executes the /home/sathiya/backup.sh script once in every 7 days.

On the day when the backup.sh job is supposed to executed, if the system is down for some reason, anacron will execute the backup.sh script 15 minutes after the system comes back up (without having to wait for another 7 days).

# cat /etc/anacrontab

7 15 test.daily /bin/sh /home/sathiya/backup.sh

START_HOURS_RANGE and RANDOM_DELAYThe above example indicates that the backup.sh script should be executed every day, with a delay of 15 mins. i.e When the laptop was started, executed it only after 15 minutes.

What happens when the laptop or desktop was not shutdown? When does the job gets executed? This is specified by the START_HOURS_RANGE environment variable in the /etc/anacrontab file.

By default this is set to 3-22 in the file. This indicates the time range from 3 a.m to 10 p.m.

# grep START /etc/anacrontab

Page 16: Linux crontab

START_HOURS_RANGE=3-22

On top of the user defined delay specified in the 2nd field of the /etc/anacrontab file, anacron also randomly adds x number of minutes. The x is defined by the RANDOM_DELAY variable in the /etc/anacrontab file.

By default this is set to 45 in the file. This means that anacron will add x minutes (randomly picked from 0 and 45), and add this to the user defined delay.

# grep RANDOM /etc/anacrontab

RANDOM_DELAY=45

Cron Vs AnacronCron and anacron has its own advantages and disadvantages. Depending on your requirement, use one of them.

Cron Anacron

Minimum granularity is minute (i.e Jobs can be scheduled to be executed every minute)

Minimum granularity is only in days

Cron job can be scheduled by any normal user ( if not restricted by super user )

Anacron can be used only by super user ( but there are workarounds to make it usable by normal user )

Cron expects system to be running 24 x 7. If a job is scheduled, and system is down during that time, job is not executed.

Anacron doesn’t expect system to be running 24 x 7. If a job is scheduled, and system is down during that time, it start the jobs when the system comes back up.

Ideal for servers Ideal for desktops and laptops

Page 17: Linux crontab

Use cron when a job has to be executed at a particular hour and minute

Use anacron when a job has to be executed irrespective of hour and minute

6 Linux Crontab Command Examples

by RAMESH NATARAJAN  on DECEMBER 14, 2011

Crontab command manages the cron table that is used by the cron daemon to execute the cron jobs. This article explains the various command line options of the crontab command.

1. Tweaking Other Users Crontab using Option -u-u stands for user. This should be followed by a valid username in the system. -u option alone doesn’t do anything. It should be combined with other options. Actually, it can be combined with any other crontab command line options.

If you don’t specify -u username, crontab commands wil be executed on the current user. For example, all of the following crontab commands will be executed on the current logged in user.

crontab -l

crontab -e

crontab -r

..

If you specify -u username, the crontab command will be executed on the given username. For example, all of the

Page 18: Linux crontab

following crontab commands will be execute on the oracle user.

crontab -u oracle -l

crontab -u oracle -e

crontab -u oracle -r

..

2. Display Cron Table using Option -l-l stands for list. This displays the crontab of the current user. Since I’m logged in as root, this will display the cron jobs of root user.

# crontab -l

53 00 * * 7 /bin/sh /home/root/bin/server-backup

To display the cron jobs of other users, combine -l with -u option.

# crontab -u oracle -l

01 00 * * * /bin/sh /home/oracle/bin/rman-backup

The 15 crontab examples explains practical ways of using the cron job entries.

Page 19: Linux crontab

3. Edit Cron Table using Option -e-e stands for edit. This allows you to edit the crontab of the current user. Since I’m logged in as root, this will automatically open root’s cron jobs in a Vim editor, and allow me to edit it.

# crontab -e

53 00 * * 7 /bin/sh /home/root/bin/server-backup

~

~

/tmp/crontab.7dgqju

As you notice from the above, /tmp/crontab.7dgqju is a temporary file created by the crontab automatically where you can edit your cron jobs.

When you save your edits and come out of the Vim editor, it will display oone of the following messages, depending on whether you made any changes or not.

# crontab -e

crontab: no changes made to crontab

Page 20: Linux crontab

# crontab -e

crontab: installing new crontab

Note: The editor that crontab uses to open the cron jobs for editing depends on the VISUAL or EDITOR environment variable. By default, it will use Vim editor on Linux environment. But you can change it using the VISUAL/EDITOR environment variable.

To edit the cron jobs of other users, combine -e with -u option.

# crontab -u oracle -e

crontab: installing new crontab

To understand the meaning of the crontab entries itself, refer to How to Run a Cron Job Every 5 Minutes (or Hours, or Days, or Months).

4. Load Crontab from a FileInstead of manually editing the crontab to add new jobs, you can also upload all the cron jobs from a file. This is helpful when you have to maintain lot of servers that has the same cron job entries.

In the following example, all the cron jobs are in the /home/root/mycronjobs.txt file.

Page 21: Linux crontab

# cat /home/root/mycronjobs.txt

53 00 * * 7 /bin/sh /home/root/bin/server-backup

01 00 * * * /bin/sh /home/root/bin/check-user-quota

To upload the mycronjobs.txt jobs to current user crontab, do the following:

# crontab /home/root/mycronjobs.txt

Validate to make sure the cron jobs are successfully uploaded.

# crontab -l

53 00 * * 7 /bin/sh /home/root/bin/server-backup

01 00 * * * /bin/sh /home/root/bin/check-user-quota

Note: Be careful while using this upload method, as this will wipe-out all the current cron job entries before uploading the new ones.

To upload the cron job from a file to another user, combine it with -u option.

# crontab -u oracle /home/oracle/mycronjobs.txt

Page 22: Linux crontab

5. Add SELinux Security using Option -s-s stands for SELinux. This will add the MLS_LEVEL variable to the crontab that contains the current SELinux security context.

To use -s option, you should upload the cron jobs from a file.

# cat /home/root/mycronjobs.txt

53 00 * * 7 /bin/sh /home/root/bin/server-backup

01 00 * * * /bin/sh /home/root/bin/check-user-quota

# crontab -s /home/root/mycronjobs/my.txt

SELINUX_ROLE_TYPE=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

53 00 * * 7 /bin/sh /home/root/bin/server-backup

01 00 * * * /bin/sh /home/root/bin/check-user-quota

Depending on your system the above will add either SELUNUX_ROLE_TYPE variable or MLS_LEVEL variable that contains the SELinux security context string. If you are not using SELinux in your environment, don’t worry about what this option does. SELinux is a separate topic of discussion, that we might cover in detail in future articles.

Page 23: Linux crontab

6. Delete All Cron Jobs using Option -r-r stands for remove. This will remove all the cron job entries of the current user as shown below.

# crontab -l

53 00 * * 7 /bin/sh /home/root/bin/server-backup

01 00 * * * /bin/sh /home/root/bin/check-user-quota

# crontab -r

# crontab -l

no crontab for root

-i stands for interactive mode. Combining -i with -r will ask you a confirmation before removing all the crontab entries.

# crontab -ir

crontab: really delete root's crontab? n

To remove the cron jobs of other users, combine -r with -u option.

Page 24: Linux crontab

# crontab -u oracle -l

01 00 * * * /bin/sh /home/oracle/bin/rman-backup

# crontab -u oracle -r

# crontab -u oracle -l

no crontab for oracle

How To Install, Edit, or Remove Cron Jobs in Batch Mode

by RAMESH NATARAJAN  on NOVEMBER 20, 2009

Question:  How can I install all the schedule jobs from a text file to the crontab? Also, can I remove all the cron jobs at once instead of removing the individual lines from the crontab?Answer: You can install, edit and remove crontab in batch mode as examples below. Also, refer to our 15 crontab examples.

1. Install Crontab in Batch ModeBy specifying the file name as an argument to crontab command, you can install the new cron jobs from a text file as shown below.

Page 25: Linux crontab

First create a text file with all your cron job entries.

$ cat cron-file.txt

* * * * * /bin/date >> /tmp/date-out

* * * * * /bin/ls >> /tmp/ls-out

Next, install the cron jobs from a text file as shown below.

$ crontab cron-file.txt

Note: This will overwrite the existing cron entries.

2. Edit crontab in Batch ModeYou can edit the crontab in batch mode using various methods (for example, using sed).

Example: Change output redirection from write to append for all cron jobs.

$ crontab -l

* * * * * /bin/date > /tmp/date-out

* * * * * /bin/ls > /tmp/ls-out

Page 26: Linux crontab

$ crontab -l | sed 's/>/>>/' | crontab -

$ crontab -l

* * * * * /bin/date >> /tmp/date-out

* * * * * /bin/ls >> /tmp/ls-out

3. Remove All cron jobs of the Current UserCrontab’s -r option removes all cron job for the current user. If you have appropriate privilege, you can even remove other user’s cron jobs using the -r option along with the -u user option.

Example: Remove the current user cron entries.

$ crontab -r

Example: Remove the specified user cron entries.

$ crontab -r -u USERNAME