Cron Vs Anacron Linux 定时任务详解

发布时间: 更新时间: 总字数:1156 阅读时间:3m 作者: IP属地: 分享 复制网址

本文介绍cron和anacron定时任务,并介绍如何在Linux上设置anacron。

在 Linux 中设置 Anacron

Anacron 是以周期定义的频率定期运行命令。 它与cron的区别如下:

  • 假设你有一个计划的任务(如备份脚本 ),每半年可以使用cron运行,可能当你睡着了,你的桌面/笔记本电脑在那个时候关闭了。 您的备份脚本将不会被执行。
  • 但是,如果您使用anacron,您可以放心,下次再次启动桌面/笔记本电脑时,将执行备份脚本。

Anacron 在 Linux 中的工作原理

anacron 作业列在 /etc/anacrontab中 ,作业可以使用以下格式进行安排(anacrontab文件中的注释必须以#开头)。

[root@xiexianbin_cn ~]# cat /etc/anacrontab
# /etc/anacrontab: configuration file for anacron

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

SHELL=/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# the maximal random delay added to the base delay of the jobs
RANDOM_DELAY=45
# the jobs will be started during the following hours only
START_HOURS_RANGE=3-22

#period in days   delay in minutes   job-identifier   command
1   5   cron.daily      nice run-parts /etc/cron.daily
7   25  cron.weekly     nice run-parts /etc/cron.weekly
@monthly 45 cron.monthly        nice run-parts /etc/cron.monthly
[root@xiexianbin_cn ~]#

说明如下:

  • period in days(期间) - 这是以天为单位指定的工作执行频率,或者每天,每周或每月@daily,@周,或@monthly一次。 您也可以使用数字:1 - 每天,7 - 每周,30 - 月和N - 天。
  • delay in minutes(延迟) - 这是在执行作业之前等待的分钟数。
  • job-identifier - 这是在日志文件中编写的作业的独特名称。
  • command(命令) - 这是要执行的命令或shell脚本。

要查看示例文件,请键入:

[root@xiexianbin_cn ~]# ll -lh /var/spool/anacron/
total 12K
-rw-------. 1 root root 9 May  6 03:49 cron.daily
-rw-------. 1 root root 9 Apr 26 03:20 cron.monthly
-rw-------. 1 root root 9 May  1 03:50 cron.weekly
[root@xiexianbin_cn ~]#

这实际上是这样的:

Anacron将检查在期间字段内的指定期间内是否已经执行作业。 如果没有,则在等待延迟字段中指定的分钟数后,执行命令字段中指定的命令。 作业执行完成后,它将使用job-identifier(timestamp文件名)字段中指定的名称将日期记录在/var/spool/anacron目录中的时间戳记文件中。

例子

每天运行/home/aaronkilik/bin/backup.sh脚本:

@daily    10    example.daily   /bin/bash /home/aaronkilik/bin/backup.sh

如果在预期运行backup.sh作业时机器关闭,anacron将在机器上电后10分钟运行,而无需再等待7天。

您应该了解的anacrontab文件中有两个重要的变量:

  • START_HOURS_RANGE - 这将设置作业启动的时间范围(即在以后几个小时内执行作业)。
  • RANDOM_DELAY - 这定义了添加到用户定义的作业延迟的最大随机延迟(默认为45)。

Anacron - /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
@daily    10    example.daily   /bin/bash /home/aaronkilik/bin/backup.sh

以下是cron和anacron的比较 ,以帮助您了解何时使用它们。

cron anacron
守护进程 非守护进程
适用于服务器机器 适用于台式机/笔记本电脑
能够每分钟运行排定的作业 只允许您每天运行排定的作业
当机器关闭时,不执行计划作业 如果机器在计划作业到期时关闭,则在下次启动机器时将执行计划作业
可以由普通用户和root使用 除非另有说明,否则只能由root使用(对具有特定配置的普通用户启用)
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数