Anacron
anacron 处理非 24 小时一直启动的 linux 系统的 crontab 的执行,并不能指定何时执行,而是以天为单位或者是开机后立即进行 anacron
的操作,它会去检查关机的时候应该但是没有执行的 crontab 任务,并执行一遍然后就停止了。通常 anacron 是以 root 用户执行的。
anacron 会去分析现在的时间和时间记录文件所记载的上次执行 anacron 的时间,若有区别,说明在某些时刻没有进行 crontab,anacron
就会开始执行未进行的任务了。它其实也是通过crontab 来执行的, anacron 的运行时间通常有两个,开机期间和写入 crontab 调度中。
Format
来看看 /etc/anacrontab 中的内容,
1 5 cron.daily run-parts --report /etc/cron.daily
分别代表 period,delay,job-identifier,command.
- period:recurrence period,1(daily), 7(weekly), 30(or @monthly, monthly), N(n days)
- delay: delay in minutes
- job-identifier: name for job's timestamp file(under
/var/spool/anacron,
contain a single line indicates the last time when the job was executed),
it should be unique. - command: command or shell script that needs to be executed.
Reference: Cron Vs Anacron: How to Setup Anacron on Linux (With an Example)
Use anacron as normal user
之所以需要这个,是由于自己写的 wonderful_bing,我要每天都能自动下载壁纸,而且有时候很长时间不关机,一直睡眠,
自然 anacron 更能胜任这一要求,但是如果简单的把它加入 anacron, 之前也说过 anacron 是以 root 运行的,壁纸还是能够下载,
但是所有者和用户组都是 root, 导致下载的壁纸无法设置成 wallpaper,以普通用户来执行 anacron 则没有问题。
$ mkdir $HOME/.anacron $ mkdir $HOME/.anacron/cron.daily $ mkdir $HOME/.anacron/cron.weekly # 根据自己需要决定 $ mkdir $HOME/.anacron/timestamps # used as the spool directory $ touch $HOME/.anacron/anacrontab
在 anacrontab 文件中加入下列内容:
# See anacron(8) and anacrontab(5) for details. SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # These replace cron's entries 1 5 user.daily nice run-parts --report $HOME/.anacron/cron.daily 7 10 user.weekly nice run-parts --report $HOME/.anacron/cron.weekly # the following is for `wonderful_bing`, a python package written by myself. 1 1 wonderful_bing env DISPLAY=:0 /usr/local/bin/wonderful_bing -d /home/lord63/pictures/bing/ 2>> /home/lord63/error # eof
把下面这行加到你的 $HOME/.profile (这样每次你登录的时候它就会自动运行了):
/usr/sbin/anacron -t ${HOME}/.anacron/anacrontab -S ${HOME}/.anacron/timestamps &> ${HOME}/.anacron/anacron.log
为了让它能够被系统的 anacron 像以正常的 anancron 运行,新建下面的文件 /etc/cron.daily/user-anacron(USERNAME 改成自己的):
1 2 3 | #!/bin/bash HOME="/home/USERNAME" su USERNAME -c "/usr/sbin/anacron -t ${HOME}/.anacron/anacrontab -S ${HOME}/.anacron/timestamps &> ${HOME}/.anacron/anacron.log" |
Reference: