Chinaunix首页 | 论坛 | 博客
  • 博客访问: 85870
  • 博文数量: 20
  • 博客积分: 1926
  • 博客等级: 上尉
  • 技术积分: 210
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-16 17:21
文章分类
文章存档

2011年(1)

2009年(19)

分类: LINUX

2009-10-08 21:14:51

调度周期任务Cron

Author: Jaylin Zhou

Date: 10/08/2009

Cron工具允许用户配置要定期运行的命令。

用户用crontab命令配置自己的任务计划,指定何种命令在何时运行。这些任务由传统的Linux守护进程——crond daemon管理。

Crontab的配置文件是/etc/crontab,其中

MAILTO=root

说明每次crond进程执行某个操作时都会给root用户发mail。也可以指定一个确定的邮箱名。

下面是主体部分:

# run-parts

01 * * * * root run-parts /etc/cron.hourly

02 4 * * * root run-parts /etc/cron.daily

22 4 * * 0 root run-parts /etc/cron.weekly

42 4 1 * * root run-parts /etc/cron.monthly

前五项分别为:分钟(0-59)、小时(0-23)、天(0-31)、月(1=Jan)、星期(0=Sun1=Mon)。

这里可以使用一些语法标记:

* 表示每次都执行;

n 表示指定的时间执行;

n1,n2... 表示指定的任何一个时间都执行;

n1-n2 表示在指定范围内都执行;

*/n 表示每个n次才执行。

第六项是执行的用户,这里是root

第七项,即run-parts /etc/cron.xxx,是具体执行哪些脚本。

/usr/bin/run-parts脚本的作用是执行一个目录下的所有脚本。

cron有关的脚本都存放在下面的几个目录里:

# cd /etc/cron

cron.d/       cron.deny     cron.monthly/ cron.weekly/  

cron.daily/   cron.hourly/  crontab      

也就是说,上面主体部分的意思是:

第一行:每小时的第一分钟执行/etc/cron.hourly/下的脚本。

第二行:每天的42分执行/etc/cron.daily/下的脚本。

第三行:每个星期日的422分执行/etc/cron.weekly/下的脚本。

第四行:每个月的1日的442分执行/etc/cron.monthly/下的脚本。

所以,如果有想添加的cron任务,就可以写到/etc/crontab下,脚本放在对应的目录下。

 

使用crontab命令

用户很少直接修改/etc/crontab文件,而是使用crontab命令来编辑自己的crontab

# crontab -e -u jaylin

no crontab for jaylin - using an empty one

crontab: installing new crontab

编辑用户jaylincrontab-e参数为编辑crontab的内容,-u参数为指定用户,如果不加-u参数则是对当前用户的crontab进行操作。

# crontab -l -u jaylin

* * * * * date

列出用户jaylincrontab-l参数为列出crontab的内容。

# crontab -r -u jaylin

# crontab -l -u jaylin

no crontab for jaylin

删除用户jaylincrontab-r参数为删除crontab的内容。

当然,也可以在用户的crontab中添加MAILTO环境变量。

注意,每个用户的crontab生成之后都会在/var/spool/cron/目录下生产一个以用户名为名字的文件。当删除了crontab之后,对应用户的文件也就不存在了。

# cat /var/spool/cron/jaylin 

* * * * * date

查看crontab是否执行了,可以通过查看/var/log/cron文件

# tail -f /var/log/cron 

Oct  8 20:39:34 localhost crontab[4306]: (root) BEGIN EDIT (jaylin)

Oct  8 20:39:45 localhost crontab[4306]: (root) REPLACE (jaylin)

Oct  8 20:39:45 localhost crontab[4306]: (root) END EDIT (jaylin)

Oct  8 20:41:14 localhost crontab[4351]: (root) BEGIN EDIT (jaylin)

Oct  8 20:41:38 localhost crontab[4351]: (root) REPLACE (jaylin)

Oct  8 20:41:38 localhost crontab[4351]: (root) END EDIT (jaylin)

Oct  8 20:41:45 localhost crond[4384]: (CRON) STARTUP (V5.0)

Oct  8 20:41:57 localhost crontab[4422]: (jaylin) BEGIN EDIT (jaylin)

Oct  8 20:41:58 localhost crontab[4422]: (jaylin) END EDIT (jaylin)

Oct  8 20:42:01 localhost crond[4425]: (jaylin) CMD (date)

Oct  8 20:43:01 localhost crond[4487]: (jaylin) CMD (date)

说明用户jaylin每一分钟都执行了一次date命令。

 

阅读(1691) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~