Linux Crontab 定时任务


一、Crontab介绍
 
crontab命令的功能是在一定的时间间隔调度一些命令的执行。
 
1.1 /etc/Crontab文件
 
在/etc目录下有一个crontab文件,这里存放有系统运行的一些调度程序。每个用户可以建立自己的调度crontab(在/var/spool/cron目录下)。
 以下是我本机上的crontab文件,
 
[root@localhost etc]# cat /etc/crontab
 SHELL=/bin/bash
 PATH=/sbin:/bin:/usr/sbin:/usr/bin
 MAILTO=root
 HOME=/
 
# 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 

二、Crontab使用说明 
 
2.1 Crontab基本语法
 
usage:  crontab [-u user] file
 
        crontab [-u user] [ -e | -l | -r ]
 
                (default operation is replace, per 1003.2)
 
        -e      (edit user's crontab)
 
        -l      (list user's crontab)
 
        -r      (delete user's crontab)
 
        -i      (prompt before deleting user's crontab)
 
        -s      (selinux context) 
 
 
其中,file是命令文件的名字。如果在命令行中指定了这个文件,那么执行crontab命令,则将这个文件拷贝到crontabs目录下;如果在命令行中没有制定这个文件,crontab命令将接受标准输入(键盘)上键入的命令,并将他们也存放在crontab目录下。
 
如果想查看Crontab更详细的语法及使用帮助,则可以通过man crontab来查看帮助。
 
2.2  Crontab 格式说明
 
      我们可以用crontab -e 添加要执行的命令。     

  添加的命令必须以如下格式:
 
  * * * * * /需执行命令的路径
 
      前五个字段可以取整数值,指定何时开始工作,第六个域是字符串,即命令字段,其中包括了crontab调度执行的命令。 各个字段之间用spaces和tabs分割。 
 
前5个字段分别表示:
 
      分钟:0-59
 
      小时:1-23
 
      日期:1-31
 
      月份:1-12
 
      星期:0-6(0表示周日)
 
 
还可以用一些特殊符号:
 
      *: 表示任何时刻
 
      ,: 表示分割
 
  -:表示一个段,如第二端里: 1-5,就表示1到5点
 
      /n : 表示每个n的单位执行一次,如第二段里,*/1, 就表示每隔1个小时执行一次命令。也可以写成1-23/1.
 
一些示例:
 
00 8,12,16 * * * /test/command.sh
 
30 2 * * * /test/command.sh
 
10 8,12,16 * * * /test/command.sh
 
10 8,12,16 * * * /test/command.sh
 
10 8,12,16 * * * /test/command.sh
 
 
 
43 21 * * * 21:43 执行
 
15 05 * * *    05:15 执行
 
0 17 * * * 17:00 执行
 
0 17 * * 1 每周一的 17:00 执行
 
0,10 17 * * 0,2,3 每周日,周二,周三的 17:00和 17:10 执行
 
0-10 17 1 * * 毎月1日从 17:00到17:10 毎隔1分钟 执行
 
0 0 1,15 * 1 毎月1日和 15日和周一的 0:00 执行
 
42 4 1 * *     毎月1日的 4:42分 执行
 
0 21 * * 1-6   周一到周六 21:00 执行
 
0,10,20,30,40,50 * * * * 每隔10分 执行
 
*/10 * * * *        每隔10分 执行
 
* 1 * * *         从1:0到1:59 每隔1分钟 执行
 
0 1 * * *         1:00 执行
 
0 */1 * * *        毎时0分 每隔1小时 执行
 
0 * * * *         毎时0分 每隔1小时 执行
 
2 8-20/3 * * *      8:02,11:02,14:02,17:02,20:02 执行
 
30 5 1,15 * *       1日和15日的5:30 执行

相关内容