Linux crontab(定时任务) 配置

crontab 命令

usage:  crontab [-u user] file
        crontab [ -u user ] [ -i ] { -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)

crontab 语法内容

# 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
字段 说明
minute 分钟,取值范围 0-59
hour 小时,取值范围 0-23
day of month 日,取值范围 1-31
month 月,取值范围 1-12,或者使用英文缩写jan, feb, mar, apr ...
day of week 星期,取值范围 0-6,0 或 7 表示星期日,或者使用英文缩写 sun, mon, tue, wed, thu, fri, sat
user-name 执行该定时任务的用户
command 具体执行的命令,可以是一个简单的命令,也可以是一个脚本,或者是一个目录,如果是一个目录,则表示执行目录中的所有脚本,目录的前面必须加上 run-parts
  • 星号(*)表示取值范围内的所有值。例如,* 在hour的位置,表示每小时执行一次。
  • 连字符(-)表示一个范围。例如,8-12表示8、9、10、11、12。
  • 逗号(,)表示分割指定的数值。例如:3,5-7,9表示3,5,6,7,9。
  • 正斜杠(/)表示步进值。例如,分钟的位置为*/5,表示每五分钟执行一次。

除了 root 用户以外的所有用户定义的 crontab 计划任务都存放在/var/spool/cron目录,通过 crontab -e 命令编辑,格式与 /etc/crontab 相同,可以不用指定 user-name。

cron 服务会每分钟检查一次 /etc/crontab/etc/cron.d//var/spool/cron/ 中的所有文件,并依此执行。

实例

  • 每隔 3 分钟执行 */3 * * * * /opt/test.sh
  • 每隔 3 小时执行 0 */3 * * * /opt/test.sh > /dev/null 2>&1
  • 每天凌晨 1 点执行 0 1 * * * /opt/test.sh
  • 每个星期天凌晨执行 0 0 * * SUN /opt/test.sh
  • 每月 1 号凌晨执行 0 0 1 * * /opt/test.sh > /dev/null 2>&1
    实例参考: how to write a crontab schedule expression for

推荐

https://crontab.guru 可以在线编辑并执行,实时查看 crontab 任务执行过程。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容