在计算机的使用过程中,经常会有一些计划中的任务需要在将来的某个时间执行,linux中提供了一些方法来设定定时任务。
crond/crontab
命令crontab用来设置、移除、列出服务crond表格,crond服务的作用类似atd,区别的地方在于crond可以设置任务多次执行。相对来说比atd更常用。
查看定时任务
# 查看主服务是否启用ps -ef|grep [c]rond# 查看root 用户定时任务sudo crontab -l -u root# 查看所有用户的定时任务for u in `cat /etc/passwd | cut -d":" -f1`;do crontab -l -u $u;done# 对于系统级别的定时任务,这些任务更加重要,大部分linux系统在/etc中包含了一系列与 cron有关的子目录:/etc/cron.{hourly,daily,weekly,monthly},目录中的文件定义了每小时、每天、每周、每月需要运行的脚本,运行这些任务的精确时间在文件/etc/crontab中指定.如下:SHELL=/bin/bashPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=rootHOME=/# run-parts01 * * * * root run-parts /etc/cron.hourly02 4 * * * root run-parts /etc/cron.daily22 4 * * 0 root run-parts /etc/cron.weekly42 4 1 * * root run-parts /etc/cron.monthly对于24小时开机的服务器来说,这些任务的定期运行,保证了服务器的稳定性。但注意到这些任务的执行一般都在凌晨,对于经常需要关机的linux计算机(如笔记本)来说,很可能在需要运行cron的时候处于关机状态,cron得不到运行,时间长了会导致系统变慢。对于这样的系统,linux引入了另一个工具anacron来负责执行系统定时任务。anacron的目的并不是完全替代cron,是作为cron的一个补充。anacron的任务定义在文件/etc/anacrontab中,如下:# /etc/anacrontab: configuration file for anacron# See anacron(8) and anacrontab(5) for details.SHELL=/bin/shPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=root# the maximal random delay added to the base delay of the jobsRANDOM_DELAY=45# the jobs will be started during the following hours onlySTART_HOURS_RANGE=3-22#period in days delay in minutes job-identifier command1 5 cron.daily nice run-parts /etc/cron.daily7 25 cron.weekly nice run-parts /etc/cron.weekly@monthly 45 cron.monthly nice run-parts /etc/cron.monthly与cron是作为守护进程运行的不同,anacron是作为普通进程运行并终止的。
