计划周期性系统作业

目标

  使用用户crontab文件来安排命令按计划重复运行。

名词定义

  • 周期性用户作业
      按计划重复运行的作业被称为周期性作业。守护进程为crond守护进程,有cronie软件包提供,且默认启用并启动。crond守护进程会读取多个配置文件以及一组系统范围内的文件。这些配置文件使用户和管理员拥有细微的控制权,可以控制应执行周期性作业的时间。

  计划任务的命令生成任何未被重定向的输出或错误,则crond守护进程将尝试使用系统中配置的邮件服务器将该输出或错误通过电子邮件发送给拥有该作业的用户。根据环境,这可能需要进行其他配置。可以将计划命令的输出或错误重定向到其他文件。

  • 计划周期性用户作业
      普通用户可以使用crontab命令来管理作业

  • crontab
    &ngsp; crontab是用来让使用者在固定时间或固定间隔执行程序之用,类似使用者的时程表。

  • 时间格式

f1 f2 f3 f4 f5 user-name command

  • 其中 f1 是表示分钟,f2 表示小时,f3 表示一个月份中的第几日,f4 表示月份,f5 表示一个星期中的第几天。program 表示要执行的程序。
  • 当 f1 为 * 时表示每分钟都要执行 program,f2 为 * 时表示每小时都要执行程序,其馀类推
  • 当 f1 为 a-b 时表示从第 a 分钟到第 b 分钟这段时间内要执行,f2 为 a-b 时表示从第 a 到第 b 小时都要执行,其馀类推
  • 当 f1 为 */n 时表示每 n 分钟个时间间隔执行一次,f2 为 */n 表示每 n 小时个时间间隔执行一次,其馀类推
  • 当 f1 为 a, b, c,… 时表示第 a, b, c,… 分钟要执行,f2 为 a, b, c,… 时表示第 a, b, c…个小时要执行,其馀类推
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
  • 使用run-part方式运行

  • /etc/anacrontab 文件使用run-part的脚本方式运行
  • /etc/cron.daily : 周期为每天运行的脚本目录
  • /etc/cron.veekly : 周期为每周运行的脚本目录
  • /etc/cron.nonthly : 周期为每月运行的脚本目录
  • /etc/cron.d/0hourly : 周期为每小时第一分钟run-part执行 /etc/cron.hourly目录中的脚本
# /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

实操演示

  • 命令:crontab

    语法:crotab -u user file
    -e : 执行文字编辑器来设定时程表,内定的文字编辑器是 VI,如果你想用别的文字编辑器,则请先设定 VISUAL 环境变数来指定使用那个文字编辑器(比如说 setenv VISUAL joe)
    -r : 删除目前的时程表
    -l : 列出目前的时程表

##打开配置文件进行配置计划任务
[root@sinfotek ~]# vim /etc/crontab 
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
* * * * * sinfotek /usr/bin/echo "$(date)"
文档更新时间: 2022-09-14 15:20   作者:xiubao yan