Linux_day05_02_计划任务

计划任务

Linux计划任务
  • 未来在某一时间点执行一次任务:at、batch
  • 周期性的运行某个任务:crond
  1. at命令

需要安装:yum -y install at

[root@localhost ~]# at --help
at: invalid option -- '-'
Usage: at [-V] [-q x] [-f file] [-mMlbv] timespec ...
       at [-V] [-q x] [-f file] [-mMlbv] -t time
       at -c job ...
       atq [-V] [-q x]
       at [ -rd ] job ...
       atrm [-V] job ...
       batch
  • 用法说明:at 参数 时间
  • 参数
    • -m:当指定的任务被完成之后,将给用户发送邮件,即使没有标准输出
    • -I:atq的别名
    • -d:atrm的别名
    • -v:显示任务将被执行的时间
    • -c:打印任务的内容到标准输出
    • -V:显示版本信息
    • -q:使用指定队列
    • -f:从指定文件读入任务,而不是从标准输入读入
    • -t:一时间参数的形式提交要运行的任务
  • 时间
    • HH::MM [YYYY-MM-DD]
    • moon, midnight, teatime
    • tomorrow
    • now + num {minutes, hours, days, weeks}
  • atq:查看计划任务
  • atrm 2:移除任务

提前启动atd.service:systemctl start atd

  1. batch命令

让系统自动选择空闲时间去执行此处指定任务

  • 用法说明:batch 参数 时间
  • 参数
    • -f:指定包含具体指令的任务文件
    • -q:指定新任务的队列名称
    • -m:任务执行完后向用户发送Email
  • 示例
batch 
at> echo 1234
at> <EOT>
job 5 at Sun Apr 28 08:49:00 2013
Linux系统任务

Linux系统则是由crond服务来控制计划任务。Linux上有许多非常多的计划性任务,所以这个服务是默认启动的。另外,由于使用者也可以设置计划任务,所以提供了使用者控制计划任务的命令crontab命令

cat /etc/crontab 

SHELL=/bin/bash	指定shell
PATH=/sbin:/bin:/usr/sbin:/usr/bin	系统执行命令的路径
MAILTO=root		任务执行通过邮件发送给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
0-30 */2 3,6,9 1 root /usr/bin/echo hello
  分 时 日 月 周 用户名 任务命令

时间

  • 特定值:给定时间点有效范围内的取值
  • *:给定时间点上有效取值范围内的所有值,表示“每…”
  • 离散取值:通过逗号进行离散取值1,3,6,9
  • 连续取值:通过减号-可以进行连续取值0-30
  • 定义步长:*/5:表示“每5…”

crontab命令

  • -l:列出所有任务
  • -e:编辑任务
  • -r:移除所有任务
  • -i:交互式
  • -u:指定用户

练习题

  1. 设置一次性计划任务在18:00时关闭系统,并查看任务信息
at 18:00
at> poweroff
at> <EOT>

atq # 查看任务信息
  1. 每天晚上的24点时打包压缩 /etc/passwd /etc/shadow /etc/group /etc/gshadow 为 file.tar.gz
crontab -e -uroot 0 0 * * * tar -czvf file.tar.gz /etc/passwd /etc/shadow /etc/group /etc/gshadow
  1. 每周一的每隔五分钟列出磁盘使用状况
crontab -e -uroot */5 * * * 1 df -Th
  1. 每天的8:30与互联网时间同步服务器pool.ntp.org同步时间
crontab -e -uroot 30 8 * * * ntpdate pool.ntp.org
  1. 通过crontab命令查看root的计划任务,通过文件查看类工具列出/var/spool/cron下对应的文件内容
crontab -l -uroot

cat /var/spool/cron/root

猜你喜欢

转载自blog.csdn.net/qq_44924544/article/details/108903885