Linux 使用 Cron 或 Anacron 进行任务自动化和调度

内容纲要

查看【Linux】专题可浏览更多内容

Cron

Cron 作业是一个非常实用的管理工具,可以在特定时间执行命令或任务。

用于用户范围的 Cron 作业的配置文件一般位于 /var/spool/cron/crontabs,用于系统范围的 Cron 作业的配置文件一般位于 /etc/crontab,不同的 Linux 发行版的路径可能有所不同

管理 Cron 作业

所以可以使用 crontab 命令进行管理:

# 查看作业列表
crontab -l

# -e 表示 edit
crontab -e
no crontab for toor - using an empty one

Select an editor.  To change later, run 'select-editor'.
  1. /bin/nano        <---- easiest
  2. /usr/bin/vim.basic
  3. /usr/bin/vim.tiny

在初次使用时可以根据提示选择你熟悉的编辑器

之后就会进入到配置文件中,在配置文件中,所有以 # 开头的行都是注释行,配置由「时间表」加「命令」组成。

「时间表」使用 unix-cron 字符串格式(* * * * *)定义,该格式表示一行中的五个字段,指示应在何时执行作业:

# 这是一条注释
<时间表> <命令>

# 示例:
# .---------------- 分钟 (0-59)
# |  .------------- 小时 (0-23)
# |  |  .---------- 日期 (1-31)
# |  |  |  .------- 月份 (1-12) 或 jan,feb,mar,apr ...
# |  |  |  |  .---- 周几 (0-6) (周日 = 0 或 7) 或 sun,mon,tue ...
# |  |  |  |  |
# *  *  *  *  * 命令

💡 最小单位支持是分钟

  • 字段可以包含星号(*),始终表示“倒数第一个”。
  • 范围是用连字符(-)分隔的两个数字,指定范围包含边界值。
  • 如果后跟一个范围,/NUMBER 会指定跳过该范围内对应的数字值。例如,可以在 Hour 字段中使用 0-23/2*/2 指定每两小时执行一次。
  • 列表是用英文逗号分隔的数字(或范围)集(,)。例如,Day of the month 字段中的 1,2,5,6 可指定在当月第 1 天、第 2 天、第 5 天和第 6 天执行一次。

几个关于「时间表」的例子:

# 每分钟运行一次
* * * * *

# 每个星期六的 23:45 (11:45 PM)
45 23 * * 6

# 每周一上午 9:00 (上午 9:00)
0 9 * * 1

# 每周日上午 04:05 (凌晨 4:05)
5 4 * * SUN

# 每个工作日的 22:00 (晚上 10:00)
0 22 * * 1-5

# 在重启后
@reboot

# 每年,等同于 0 0 1 1 * 或 @annually
@yearly

# 每月,等同于 0 0 1 * *
@monthly

# 每周,等同于 0 0 * * 0
@weekly

# 每日,等同于 0 0 * * * 或 @midnight
@daily

# 每小时,等同于 0 * * * *
@hourly

将时间表与命令结合:

# 命令
* * * * * echo "hello world" >> ~/hello.txt

# 或脚本
* * * * * /opt/hello.sh

「时间表」很好理解,但对一些人来说可能用的情况很少就难以记住,不过好在也有一些网站可以帮助我们计算出时间表,你可以访问以下网站获取帮助:

指定用户

crontab 是根据系统环境来创建针对用户的配置文件,如果身处 root 帐户,可以使用 -u 选项指定用户:

# 指定用户 tom 的一些 cron 作业
crontab -e -u tom

删除当前用户 Cron 配置

crontab -r

Anacron

Anacron 与 Cron 类似,但一般用于不是一直处于启动状态的系统,比如家用电脑。

sudo vim /etc/anacrontab
# /etc/anacrontab: configuration file for anacron

# See anacron(8) and anacrontab(5) for details.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
HOME=/root
LOGNAME=root

# These replace cron's entries
1       5       cron.daily      run-parts --report /etc/cron.daily
7       10      cron.weekly     run-parts --report /etc/cron.weekly
@monthly        15      cron.monthly    run-parts --report /etc/cron.monthly

Anacron 的配置格式为:

<运行频率 (天)> <运行延迟 (分钟)> <名称标识> <命令>

# 每三天,在系统启动后或使用 anacrontab 命令等待 15 分钟执行一个脚本
3 15 backup /opt/backup.sh
  • 「名称标识」会存储在 /var/spool/anacron/ 目录下,文件内容是执行作业时的时间戳;
  • Anacron 也可以使用 @daily@weekly@monthly

Anacron 与 Cron 的一个区别用法在于,例如说你使用 Cron 制定在每周日晚 8 点更新系统,但这周日你出去玩了晚上 8 点电脑处于关机状态,那么这周就没有更新上,而使用 Anacron 就可以确保你在下次启动系统后执行该任务。