Linux 定时任务

通过 crontab 命令,我们可以在固定的间隔时间执行指定的系统指令或 shell script 脚本。时间间隔的单位可以是分钟、小时、日、月、周及以上的任意组合。

crontab

1
crontab [-u user] [-l | -r | -e] [-i]

默认的 cron 服务存储在 /var/spool/cron/ 目录下,以用户名为文件名存储。

crontab 常用参数

  • -u user:指定某个用户的 crontab 服务,缺省时为当前用户;
  • -l:列出某个用户的 crontab 服务,缺省时为当前用户;
  • -r:删除某个用户的 crontab 服务(即删除 /var/spool/cron/ 的某个文件),缺省时为当前用户。不可恢复
  • -e:编辑某个用户的 crontab 服务,缺省时为当前用户;
  • -i:在删除时给出确认提示。

crontab 编辑内容

使用 crontab -e 打开当前用户的 crontab 服务文件,使用如下模板书写。

1
2
3
4
5
6
7
#!/bin/bash

# comment
crontab command here!

# comment
crontab command here!

保持良好的 shell 规范是一个好习惯

  • 所有的 shell 脚本首行需书写 Shebang#!/bin/bash,可通过 ps -p $$ 查看当前 bash
  • 保持注释:可以将 crontab 的注释格式写为 2019-10-13 root comment,可以清楚的看到时间、创建用户、命令示意;
  • 合适的空行:不同的命令之间空一行可以更加清楚。

crontab 日期格式

每一个 crontab 命令共有 6 列内容,分别是:

  1. 分钟:00-59* 表示每分钟;
  2. 小时:00-23* 表示每小时;
  3. 日:01-31* 表示每天;
  4. 月:01-12* 表示每月;
  5. 星期:0-7* 表示每星期;
  6. 命令:要运行的命令。

如一个 crontab 文件实现两个定时任务:

  1. 每分钟把系统当前时间写入某文件。若系统挂了,可通过文件看到系统最终的正常运行时间;
  2. 每月初第一天的早上六点到八点每半小时将某目录列出到某文件。
1
2
3
4
5
6
7
#!/bin/bash

# 2019-10-12 root Write running date to '/root/date.log'
* * * * * date > /root/crontab.log

# 2019-10-13 root List '/etc/' to '/root/etc_content.log'
00,30 06-08 01 * * date >> /root/etc_content.log && echo '/etc/ cotent:' >> /root/etc_content.log && ls /etc >> /root/etc_content.log && echo -e '\n' >> /root/etc_content.log

清理邮件日志

每条任务调度执行完毕,系统都会将任务输出信息通过电子邮件的形式发送给当前系统用户,将产生大量的垃圾信息。可通过两种方式来处理。

重定向邮件日志

对于每条 crontab 命令,可以通过如下方式来重定向邮件日志:

1
command > /dev/null 2>&1

即重定向到位桶(bit bucket),相当于将 stdoutstderr 直接丢弃。

定义收件人为空

若整个 crontab 文件都不需要生成邮件日志,可通过在文件头部定义邮件收件人为空来限制整个 crontab 服务:

1
2
3
4
5
6
7
8
#!/bin/bash
MAILTO=""

# comment
crontab command here!

# comment
crontab command here!

参考

https://linuxtools-rst.readthedocs.io/zh_CN/latest/tool/crontab.html