Linux crontab

1 背景知识

Linux crontab常见于Unix类Unix的操作系统之中,用于设置周期性被执行的指令。该命令从标准输入设备读取指令,并将其存放于crontab文件中,以供之后读取和执行。该词来源于希腊语 chronos(χρ?νο?),原意是时间。通常,crontab储存的指令被守护进程激活, crond常常在后台运行,每一分钟检查是否有预定的作业需要执行。这类作业一般称为cron jobs。

当安装完成操作系统之后,默认便会启动此任务调度命令。crond 命令每分钟会定期检查是否有要执行的工作,如果有要执行的工作便会自动执行该工作。

Warning

新创建的 cron 任务,不会马上执行,至少要过 2 分钟后才可以,当然你可以重启 cron服务来马上执行。

2 crontab 基本格式

*    *    *    *    *   command
-    -    -    -    -
|    |    |    |    |
|    |    |    |    +----- 星期中星期几 (0 - 6) (星期天 为0)
|    |    |    +---------- 月份 (1 - 12) 
|    |    +--------------- 一个月中的第几天 (1 - 31)
|    +-------------------- 小时 (0 - 23)
+------------------------- 分钟 (0 - 59)

3 crontab 常见用法

  1. 每晚的 21:30 重启apache。
30 21 * * * /usr/local/etc/rc.d/lighttpd restart
  1. 每月1、10、22日的4 : 45重启apache。
45 4 1,10,22 * * /usr/local/etc/rc.d/lighttpd restart
  1. 每周六、周日的1 : 10重启apache。
10 1 * * 6,0 /usr/local/etc/rc.d/lighttpd restart
  1. 每天18 : 00至23 : 00之间每隔30分钟重启apache。
0,30 18-23 * * * /usr/local/etc/rc.d/lighttpd restart
  1. 每星期六的11 : 00 pm重启apache。
0 23 * * 6 /usr/local/etc/rc.d/lighttpd restart
  1. 每一小时重启apache 。
* */1 * * * /usr/local/etc/rc.d/lighttpd restart
  1. 晚上11点到早上7点之间,每隔一小时重启apache 。
* 23-7/1 * * * /usr/local/etc/rc.d/lighttpd restart
  1. 每月的4号与每周一到周三的11点重启apache 。
0 11 4 * mon-wed /usr/local/etc/rc.d/lighttpd restart
  1. 一月一号的4点重启apache 。
0 4 1 jan * /usr/local/etc/rc.d/lighttpd restart
Warning

当程序在你所指定的时间执行后,系统会寄一封信给你,显示该程序执行的内容,若是你不希望收到这样的信,请在每一行空一格之后加上 > /dev/null 2>&1 即可

4 crontab 命令

4.1 crontab file

用指定的文件替代目前的crontab 。

crontab file [-u user] 

4.2 crontab user

crontab [ -u user ] { -l | -r | -e } 

5 crontab 环境变量问题

5.1 问题原因

如果我们使用 crontab 来定时执行脚本,无法执行,但是如果直接通过命令(如:./test.sh)又可以正常执行,这主要是因为无法读取环境变量的原因。

5.2 解决方案

  1. 所有命令需要写成绝对路径形式。
/usr/local/bin/docker
  1. 在 shell 脚本开头使用以下代码。
#!/bin/sh
. /etc/profile
. ~/.bash_profile
  1.  /etc/crontab 中添加环境变量,在可执行命令之前添加命令 . /etc/profile;/bin/sh,使得环境变量生效,例如:
20 03 * * * . /etc/profile;/bin/sh /var/www/runoob/test.sh