在计算机的使用过程中,经常会有一些计划中的任务需要在将来的某个时间执行,linux中提供了一些方法来设定定时任务。

crond/crontab

命令crontab用来设置、移除、列出服务crond表格,crond服务的作用类似atd,区别的地方在于crond可以设置任务多次执行。相对来说比atd更常用。

查看定时任务

  1. # 查看主服务是否启用
  2. ps -ef|grep [c]rond
  3. # 查看root 用户定时任务
  4. sudo crontab -l -u root
  5. # 查看所有用户的定时任务
  6. for u in `cat /etc/passwd | cut -d":" -f1`;do crontab -l -u $u;done
  7. # 对于系统级别的定时任务,这些任务更加重要,大部分linux系统在/etc中包含了一系列与 cron有关的子目录:/etc/cron.{hourly,daily,weekly,monthly},目录中的文件定义了每小时、每天、每周、每月需要运行的脚本,运行这些任务的精确时间在文件/etc/crontab中指定.
  8. 如下:
  9. SHELL=/bin/bash
  10. PATH=/sbin:/bin:/usr/sbin:/usr/bin
  11. MAILTO=root
  12. HOME=/
  13. # run-parts
  14. 01 * * * * root run-parts /etc/cron.hourly
  15. 02 4 * * * root run-parts /etc/cron.daily
  16. 22 4 * * 0 root run-parts /etc/cron.weekly
  17. 42 4 1 * * root run-parts /etc/cron.monthly
  18. 对于24小时开机的服务器来说,这些任务的定期运行,保证了服务器的稳定性。但注意到这些任务的执行一般都在凌晨,对于经常需要关机的linux计算机(如笔记本)来说,很可能在需要运行cron的时候处于关机状态,cron得不到运行,时间长了会导致系统变慢。对于这样的系统,linux引入了另一个工具anacron来负责执行系统定时任务。
  19. anacron的目的并不是完全替代cron,是作为cron的一个补充。anacron的任务定义在文件/etc/anacrontab中,如下:
  20. # /etc/anacrontab: configuration file for anacron
  21. # See anacron(8) and anacrontab(5) for details.
  22. SHELL=/bin/sh
  23. PATH=/sbin:/bin:/usr/sbin:/usr/bin
  24. MAILTO=root
  25. # the maximal random delay added to the base delay of the jobs
  26. RANDOM_DELAY=45
  27. # the jobs will be started during the following hours only
  28. START_HOURS_RANGE=3-22
  29. #period in days delay in minutes job-identifier command
  30. 1 5 cron.daily nice run-parts /etc/cron.daily
  31. 7 25 cron.weekly nice run-parts /etc/cron.weekly
  32. @monthly 45 cron.monthly nice run-parts /etc/cron.monthly
  33. cron是作为守护进程运行的不同,anacron是作为普通进程运行并终止的。