shell 脚本控制与计划任务
一、脚本优先级控制
可以使用nice和renice调整脚本优先级
避免出现不可控的死循环
死循环导致CPU占用过高
死循环导致死机
fork炸弹:
.(){.|.&};.
二、捕捉信号
捕获信号脚本的编写
- kill 默认会发送15号信号给应用程序
- ctrl + c 发送2号信号给应用程序
- 9号信号不可阻塞
# 信号脚本
#!/bin/bash
# 捕获15号信号
trap "echo sig 15" 15
# 捕获2号信号
trap "echo sig 2" 2
三、计划任务
计划任务:让计算机在指定的时间运行程序
1.一次性计划任务(at)
-
查看当前系统的时间:
[root@iZbp1e44zna0rzyna76eszZ lvhuiqi]# date Sat Jan 2 20:29:07 CST 2021
-
在指定的时间内,执行指定的shell命令:
# 使用at xx:xx [root@iZbp1e44zna0rzyna76eszZ lvhuiqi]# at 20:31 warning: commands will be executed using /bin/sh # 将hello 输出到/home/lvhuiqi/hello.txt 文件中 at> echo hello > /home/lvhuiqi/hello.txt # ctrl + d 进行提交 at> <EOT> job 2 at Sat Jan 2 20:31:00 2021
ctrl + d 进行提交
-
查看当前at未执行的shell:
[root@iZbp1e44zna0rzyna76eszZ lvhuiqi]# atq 1 Sat Jan 2 20:39:00 2021 a root 2 Sat Jan 2 20:31:00 2021 a root # 这条是上述设计的
使用atq查看一次性执行的内容
-
校验是否在指定时间输出shell命令:
[root@iZbp1e44zna0rzyna76eszZ lvhuiqi]# cat /home/lvhuiqi/hello.txt hello
-
删除at中未执行的shell命令:
[root@iZbp1e44zna0rzyna76eszZ lvhuiqi]# atrm 1
atrm num 可指定删除at中的信息
2.周期性计划任务
-
cron 配置方式:
- crontab -e
-
查看现有的计划任务:
- crontab -l
-
配置格式:
- 分钟 小时 日期 月份 星期
执行命令
注意:命令的路径问题
- 分钟 小时 日期 月份 星期
# 1.执行命令:crontab -e 打开cron配置方式
[root@iZbp1e44zna0rzyna76eszZ lvhuiqi]# crontab -e
# 每一分钟执行一次命令
* * * * * /usr/bin/date >> /home/lvhuiqi/hello.txt
如果想使用到秒的,需要另外安装三方包
# 星期一或星期五执行命令
* * * * 1,5 /usr/bin/date >> /home/lvhuiqi/hello.txt
# 星期一到星期五执行命令
* * * * 1-5 /usr/bin/date >> /home/lvhuiqi/hello.txt
查看 date的命令:
[root@iZbp1e44zna0rzyna76eszZ lvhuiqi]# which date
/usr/bin/date
查看cron的日志:tail -f /var/log/cron
# 1月1日下午15点整,执行脚本
0 15 1 1 * /usr/bin/date >> /home/lvhuiqi/hello.txt
注意:时间整点操作分钟必须为
0