日期:2014-05-16  浏览次数:20727 次

我使用过的Linux命令之crontab - 设置例行任务(类似于Windows中的任务计划)

我使用过的Linux命令之crontab - 设置例行任务(类似于Windows中的任务计划)


本文链接:http://codingstandards.iteye.com/blog/1140475 ? (转载请注明出处)

?

用途说明

crontab命令用于设置例行任务,类似于Windows中的任务计划。我们常用它来设置如下定时执行的任务:

  • 进行时间同步:ntpdate
  • 进行数据统计:mysql, sqlplus
  • 检查磁盘空间:df
  • 监控CPU使用:vmstat
  • 检查某些程序是否还在运行,重新启动:ps, service xxx start
  • 杀掉某些运行时间过长的进程:kill
  • 定时发送邮件:mail
  • 清理日志:find & rm
  • 清除数据库中的历史记录:delete from xxx where date <= n days before
  • 备份数据库:mysqldump
  • 自动系统更新:yum
  • ...

?

常用参数

格式:crontab -l

参数小写L,用于显示crontab中设置的任务情况。

?

格式:crontab -e

使用文本编辑器(通常是vi)编辑任务列表。

?

任务格式要点如下:

以#号开头的行是注释:但是与shell脚本不同的是,注释只能单独写在一行,不能与任务或环境变量设置写在同一行。

空行将被忽略;

环境变量设置:name = value,与shell脚本不同的是:等号前后可以加空格。

任务由六部分组成:小时 分钟 日期 月份 星期 程序及参数

前面五个部分用来设置任务执行的频次:

可以设置为*,比如分钟设置为*是表示每分钟;

也可以设置为具体的数值,比如小时设置为9表示9点的时候;

还可以设置多个数值,以逗号分隔,比如日期设置为5,15,25表示匹配这三个日期之一;

但是有一点要切记:前面四项的关系之间为and的关系,即需要同时满足;但星期那一项与前面月份日期是or的关系(被人称之为“冲突的逻辑”)。

?

任务的六个组成部分:

1)分(0-59)
2)时(0-23)
3)日(1-31)
4)月(1-23,或者英文名)
5)周(0-7,或者英文名,0和7均表示周日)
6)要执行的内容:包括程序名称和参数,但要注意%的使用,后面有讲到。

?

关于前五段:时间和日期
1)表示任意:* 号表示 “任意”(first-last)。
2)指定数字,表示指定的时间。
3)指定段,表示“开始-结束”内包含的数:比如3-6,表示3,4,5,6
4)指定列表:比如 “1,2,3,4″,”0-4,8-12″
5)指定“步长”:8-14/2 表示8,10,12,14

?

关于百分号%

%意味着命令行的结束。%后面的内容将被当做命令的标准输入,同时%又相当于换行。

man 5 crontab 写道
The "sixth" field (the rest of the line) specifies the command to be run. The entire command portion of the
line, up to a newline or % character, will be executed by /bin/sh or by the shell specified in the SHELL vari-
able of the cronfile. Percent-signs (%) in the command, unless escaped with backslash (\), will be changed
into newline characters, and all data after the first % will be sent to the command as standard input.

?

“%”在crontab文件中,有“结束命令行”、“换行”、“重定向”的作用,比如:
0 22 * * 1-5 mail -s “It’s 10:00 pm” joe%Joe,%%Where are your kids?%
将会在周一至周五的22:00发送一分内容为:
Joe,<换行>

<换行>

Where are your kids?<换行>

如果在命令行中确实需要%,比如date命令中指定日期时间的输出格式,那么就需要加上\进行转义。

0 4 * * *? /opt/cron/mysql_dump.sh ? ?> /srv/logs/`date +\%y-\%m-\%d`.dump.log

?

关于crontab的帮助:

man crontab????? 命令行的帮助

man 5 crontab?? 任务定义格式

?

crontab手册页中的示例 (EXAMPLE CRON FILE)

man 5 crontab 写道
# use /bin/sh to run commands, no matter what /etc/passwd says
SHELL=/bin/sh
# mail any output to ‘paul’, no matter whose crontab this is
MAILTO=paul
#
# run five minutes after midnight, every day
5 0 * * * $HOME/bin/daily.job >> $HOME/tmp/out 2>&1
# run at 2:15pm on the first of every month -- output mailed to paul
15 14 1 * * $HOME/bin/monthly
# run at 10 pm on weekdays, annoy Joe
0 22 * * 1-5 mail -s "It’s 10pm" joe%Joe,%%Where are your kids?%
23 0-23/2 * * * echo "run 23 minutes after midn, 2am, 4am ..., everyday"
5 4 * * sun echo "run at 5 after 4 every sunday"
?

?

符号@开头的特殊时间 ,比如 @reboot表示启动之后执行一次。

man 5 crontab 写道
These special time specification "nicknames" are su