crontab使用

From Wikipedia, the free encyclopedia

 
Jump to: navigation, search

The crontab command, found in Unix and Unix-like operating systems, is used to schedule commands to be executed periodically. It reads a series of commands from standard input and collects them into a file also known as a "crontab" which is later read and whose instructions are carried out. The name is derived from Greek chronos (χρόνος), meaning time.

Generally, the schedules modified by crontab are enacted by a daemon, crond, which runs constantly in the background and checks once a minute to see if any of the scheduled jobs need to be executed. If so, it executes them. These jobs are generally referred to as cron jobs.

Contents

[hide]
<script type="text/javascript"> // </script>

[edit] crontab files

The crontab files are where the lists of jobs and other instructions to the cron daemon are kept. Users can have their own individual crontab files and often there is a systemwide crontab file (usually in /etc or a subdirectory of /etc) which is also used but can only be edited by the system administrator(s).

Each line of a crontab file follows a particular format as a series of fields, separated by spaces and/or tabs. Each field can have a single value or a series of values.

[edit] Operators

There are several ways of specifying multiple date/time values in a field:

  • The comma (',') operator specifies a list of values, for example: "1,3,4,7,8"
  • The dash ('-') operator specifies a range of values, for example: "1-6", which is equivalent to "1,2,3,4,5,6"
  • The asterisk ('*') operator specifies all possible values for a field. For example, an asterisk in the hour time field would be equivalent to 'every hour'.

There is also an operator which some extended versions of cron support, the slash ('/') operator, which can be used to skip a given number of values. For example, "*/3" in the hour time field is equivalent to "0,3,6,9,12,15,18,21"; "*" specifies 'every hour' but the "/3" means that only the first, fourth, seventh...and such values given by "*" are used.

[edit] Fields

# Use the hash sign to prefix a comment
# +---------------- minute (0 - 59)
# | +------------- hour (0 - 23)
# | | +---------- day of month (1 - 31)
# | | | +------- month (1 - 12)
# | | | | +---- day of week (0 - 7) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed

Notes:

  1. For "day of the week" (field 5), both 0 and 7 are considered Sunday, though some versions of Unix such as AIX do not list "7" as acceptable in the man page.
  2. Counterintuitively, if both "day of month" (field 3) and "day of week" (field 5) are present on the same line, then the command is executed when either is true. See the examples below.

The sixth and subsequent fields (i.e., the rest of the line) specify the command to be run.

[edit] Examples

[edit] Crontab file for adm user on AIX system
#=================================================================
# SYSTEM ACTIVITY REPORTS
# Activity reports every 20 mins 8am-5:40pm, 11-11:40pm on weekdays.
# Activity reports every hour on Saturday and Sunday.
# 6pm-7am activity reports every hour during weekdays.
# summary prepared at 18:05 every weekday.
#=================================================================
0,20,40 8-17,23 * * 1-5 /usr/lib/sa/sa1 1200 3
0 * * * 0,6 /usr/lib/sa/sa1
0 18-7 * * 1-5 /usr/lib/sa/sa1
5 18 * * 1-5 /usr/lib/sa/sa2 -s 8:00 -e 18:01 -i 3600 -ubcwyaqvm

[edit] Common mistakes
  • One of the most common mistakes happens when creating a new cron job for testing purposes. When doing this, the run time must be at least two minutes into the future, as the tab only reloads at the next minute mark after being edited on some systems. For instance, if the time is now 12:05, the earliest you can schedule a job would be 12:07, as the tab would reload at 12:06:01. You can overcome this though by restarting your cron service for faster testing.
  • A common user mistake is assuming that the environment variables are the same for the user shell and the process launched.
  • A mistake which cannot be found in the man page of crontab, is to launch an X Window application from crontab. The problem is that crontab has no clue if you're running X or not; its main purpose is to run console commands. There are two solutions for this:
    • in your crontab file, insert on the first line DISPLAY=:0.0
    • when running your application, append --display :0.0, for example, "/usr/bin/audacious --display :0.0". The value :0.0 is given here as an example. You can find yours by running, in console: "echo $DISPLAY".
  • Another common mistake is to use unescaped % in your command; you have to escape them:
# Incorrect:
1 2 3 4 5 touch ~/error_`date "+%Y%m%d"`.txt

The daemon emails message with information: /bin/sh: unexpected EOF while looking for `''

# Correct:
1 2 3 4 5 touch ~/right_$(date +/%Y/%m/%d).txt

# Also correct, with single quotes:
1 2 3 4 5 touch ~/error_$(date '+%Y%m%d').txt

# Overdosed. This touches something like ~/error_/2006/04/03.txt
1 2 3 4 5 touch ~/error_$(date '+/%Y/%m/%d').txt
  • Below is another common error:
# Prepare for the daylight saving time shift
59 1 1-7 4 0 /root/shift_my_times.sh

At first glance it might look like this will run the script shift_my_times.sh at 1:59 am on the first Sunday of April. This, however, is not correct.

Unlike all of the other fields the third and fifth fields are actually an OR operation. So it will run at 1:59 am each day from the April 1st to April 7th, in addition to every remaining Sunday in April.

Here is one way this can be rewritten:

# Prepare for the daylight saving time shift
59 1 1-7 4 * test `date +/%w` = 0 && /root/shift_my_times.sh
  • Another common error is putting a cron job to be run every two hours:
# adds date to a log file
* 0,2,4,6,8,10,12,14,16,18,20,22 * * * date >> /var/log/date.log

The above will schedule the cron job to be run every minute of every even hour in the day.

The correct way of specifying a cron job would be to:

# runs the date command every even hour at the top of the hour
0 0,2,4,6,8,10,12,14,16,18,20,22 * * * date >> /var/log/date.log
# an even better way (not compatible with all crons)
0 */2 * * * date >> /var/log/date.log
  • Other errors stem from permissions not being set correctly:

The crontab files are often found in the /var/spool/cron/ directory. If your user has no read permissions for /var/spool/cron/yourUserName, then the command crontab -e will produce an error. Similarly, if your user does not have write permissions for your crontab, you cannot save changes to the crontab.

[edit] Disabling email

If any output is produced by a command executed from a crontab, the cron daemon will normally email the user that output.

  • To silence any particular command, you may redirect its output to /dev/null. To stop receiving email output from crontab, append the following to any command. This will redirect stdout and stderr to null, so you will not receive any mails:
>/dev/null 2>&1
  • You may also choose to receive mails only when an error occurs. In this case, only redirect stdout to null like this:
>/dev/null
  • Under the commonly used Vixie cron, you can also turn off email notification for all of a particular user's cronjobs by adding this line to the beginning of their crontab:
MAILTO=""

[edit] Enabling the jobs

To actually schedule the jobs you must submit them to the cron daemon using the command crontab. The easiest and most often used method is to issue the command crontab -e, which will open the default crontab file with a text editor. Once the user has made the desired changes, saving and quitting that file will automatically enable the jobs. Alternatively, one can first generate a file with the desired configuration, and then specify that file to crontab. The latter is achieved by executing crontab filename, where "filename" is the name of the file we just created.

 

crontab命令使用2007年05月14日 星期一 上午 10:06名称 : crontab
使用权限 : 所有使用者
使用方式 :
crontab [ -u user ] file
crontab [ -u user ] { -l | -r | -e }
说明 :
crontab 是用来让使用者在固定时间或固定间隔执行程序之用,换句话说,也就是类似使用者的时程表。-u user 是指设定指定 user 的时程表,这个前提是你必须要有其权限(比如说是 root)才能够指定他人的时程表。如果不使用 -u user 的话,就是表示设定自己的时程表。
参数 :
crontab -e : 执行文字编辑器来设定时程表,内定的文字编辑器是 VI,如果你想用别的文字编辑器,则请先设定 VISUAL 环境变数来指定使用那个文字编辑器(比如说 setenv VISUAL joe)
crontab -r : 删除目前的时程表
crontab -l : 列出目前的时程表
crontab file [-u user]-用指定的文件替代目前的crontab。
时程表的格式如下 :
f1 f2 f3 f4 f5 program
其中 f1 是表示分钟,f2 表示小时,f3 表示一个月份中的第几日,f4 表示月份,f5 表示一个星期中的第几天。program 表示要执行的程序。
当 f1 为 * 时表示每分钟都要执行 program,f2 为 * 时表示每小时都要执行程序,其馀类推
当 f1 为 a-b 时表示从第 a 分钟到第 b 分钟这段时间内要执行,f2 为 a-b 时表示从第 a 到第 b 小时都要执行,其馀类推
当 f1 为 */n 时表示每 n 分钟个时间间隔执行一次,f2 为 */n 表示每 n 小时个时间间隔执行一次,其馀类推
当 f1 为 a, b, c,... 时表示第 a, b, c,... 分钟要执行,f2 为 a, b, c,... 时表示第 a, b, c...个小时要执行,其馀类推
使用者也可以将所有的设定先存放在档案 file 中,用 crontab file 的方式来设定时程表。

例子1 :
#每天早上7点执行一次 /bin/ls :
0 7 * * * /bin/ls
在 12 月内, 每天的早上 6 点到 12 点中,每隔3个小时执行一次 /usr/bin/backup :
0 6-12/3 * 12 * /usr/bin/backup
周一到周五每天下午 5:00 寄一封信给 alex@domain.name :
0 17 * * 1-5 mail -s "hi" alex@domain.name < /tmp/maildata
每月每天的午夜 0 点 20 分, 2 点 20 分, 4 点 20 分....执行 echo "haha"
20 0-23/2 * * * echo "haha"
注意 :
当程序在你所指定的时间执行后,系统会寄一封信给你,显示该程序执行的内容,若是你不希望收到这样的信,请在每一行空一格之后加上 > /dev/null 2>&1 即可

例子2 :
#每天早上6点10分
10 6 * * * date
#每两个小时
0 */2 * * * date
#晚上11点到早上8点之间每两个小时,早上8点
0 23-7/2,8 * * * date
#每个月的4号和每个礼拜的礼拜一到礼拜三的早上11点
0 11 4 * mon-wed date
#1月份日早上4点
0 4 1 jan * date


...
 

常见陷阱

每个SA、DBA 或者是普通的 Unix 用户,在第一次使用 Crontab 的时候都会遇到问题. 运行 Crontab 的常见错误包括如下几种:

1) 出于测试目的新创建了一条 Cron JOB, 时间间隔必须超过两分钟,否则 JOB 将调度不到。如果必须忽略这两分钟的载入配置时间差,可以通过重新启动 Cron Daemon 做到。

2) 从 Crontab 中启动 X Window 程序需要注意的事项:所以要么在程序前初始化 "DISPLAY=:0.0", 要么在应用程序后面追加参数 --display :0.0

3) 命令中的 % 必须做转义处理: /% .我个人的意见是不要在命令行里带这个参数,干脆写到脚本里,然后调度该脚本即可。

其实我倒是认为使用 Crontab 最常见的一个问题往往是因为环境变量不对。经常会看到论坛里有人问:为什么我的 Crontab 创建了不执行? 准备创建一条 Cron JOB 的时候,很多人都喜欢在命令行下运行一遍,因为这个时候环境变量是随着 Shell 自动带进来,在 Crontab 中则可能因为找不到正确的环境变量,JOB 就不能执行。这个小问题就像出天花,一次教训之后就都记得了。

必须使用的一则技巧

每条 JOB 执行完毕之后,系统会自动将输出发送邮件给当前系统用户。日积月累,非常的多,甚至会撑爆整个系统。所以每条 JOB 命令后面进行重定向处理是非常必要的: >/dev/null 2>&1 。前提是对 Job 中的命令需要正常输出已经作了一定的处理, 比如追加到某个特定日志文件。

附: Crontab 的格式说明如下:

* 逗号(',') 指定列表值。如: "1,3,4,7,8"
* 中横线('-') 指定范围值 如 "1-6", 代表 "1,2,3,4,5,6"
* 星号 ('*') 代表所有可能的值

Linux(开源系统似乎都可以)下还有个 "/" 可以用. 在 Minute 字段上,*/15 表示每 15 分钟执行一次. 而这个特性在商业 Unix ,比如 AIX 上就没有.

# Use the hash sign to prefix a comment
# +---------------- minute (0 - 59)
# | +------------- hour (0 - 23)
# | | +---------- day of month (1 - 31)
# | | | +------- month (1 - 12)
# | | | | +---- day of week (0 - 7) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值