crontab 定时任务

1. 通过编辑  /etc/crontab 文件(文件中有对格式及取值的描述),新建定时任务。如下:

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
*/1 * * * * hdfs /opt/test/test.sh

  以上最后一行是添加的一个定时任务,如果要再建一个,可以再添加一行。如果把所有用户的所有定时任务都写在这个文件里,可以统一管理。缺点是别的用户有可能会修改别的用户的定时任务。除非只让 root 用户有修改此文件的权限,但是用户自己添加或修改定时任务则需要通过 root 用户操作。

     对文件内容的前5项的附加说明(以第一位分钟为例):

     *  代表任意值

     */2  代表每2分钟执行一次

     5,10,15  代表每到 5分钟, 10分钟, 15分钟执行一次。

下面是几个具体的示例:

    

#每分钟执行一次 /opt/test.sh 脚本
*/1 * * * * /opt/test.sh

#每天的 00:01 分执行一次脚本
1 0 * * * /opt/test.sh

#周一到周五的 23:59 分执行一次脚本
59 23 * * 1-5 /opt/backup.sh

#效果同上一条
59 23 * * 1,2,3,4,5 /opt/backup.sh

2. Crontab 选项:

crontab –e : 修改 crontab 文件. 如果文件不存在会自动创建。 
crontab –l : 显示 crontab 文件。 
crontab -r : 删除 crontab 文件。
crontab -ir : 删除 crontab 文件前提醒用户。

 crontab -e 只能创建是当前用户自己的定时任务。文件内容的格式详见 /etc/crontab 的内容。

原文地址:https://www.cnblogs.com/langfanyun/p/10487717.html