目录
一、计划任务
按照计划准时准点去执行任务
任何脚本都可以配合计划任务来执行,做到定时完成某些事情
1.1 【导入】游戏服务器资源分析
1.2 为什么需要计划任务
可以自动执行,不需要人干预,解放了人力,提高工作效率
1.3 Linux里的计划任务
crond进程:负责Linux里执行计划任务的程序,在内存里一直运行的程序(守护进程)。不要关闭
每隔一分钟去检查Linux系统里的计划任务,最短时间间隔:一分钟
使用crontab命令调用crond进程,设置按固定周期(如每天、每周等)重复执行预先计划好的任务。
#查看crond进程是否存在
[root@localhost ~]# ps aux|grep crond
root 698 0.0 0.1 126384 1672 ? Ss 15:46 0:00 /usr/sbin/crond -n
root 1857 0.0 0.0 112824 988 pts/0 R+ 16:58 0:00 grep --color=auto crond
#重启
[root@localhost ~]# service crond restart
Redirecting to /bin/systemctl restart crond.service
#停止
[root@localhost ~]# service crond stop
#在centos7中真正执行的命令
Redirecting to /bin/systemctl stop crond.service
#启动
[root@localhost ~]# service crond start
Redirecting to /bin/systemctl start crond.service
【注】systemctl stop crond和service crond stop时等价的
1.4 创建计划任务
(Linux系统里可以定制很多计划任务,一行一个计划任务)
crontab是创建计划任务的命令
crontab -e 编辑计划任务
crontab -l 查看计划任务
1.4.1 cron命令格式
【格式如下:15行】
[root@localhost ~]# cat /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
[root@localhost ~]#
* 表示任意时间
1.4.2 时间数值的表示方法
【翻译时间从右到左】
===示例
0 17 * * 1-5 ==》周一到周五每天17:00
30 8 * * 1,3,5 ==》周一、三、五的8:30
0 8-18 * * * ==》每天8点到18点整
0 12 */3 * * ==》每隔3天的12点整
===
1.4.3 实例+具体操作
【题目】
每天23:00备份一次,使用计划任务执行
备份脚本:/root/lianxi/backup_log.sh
【步骤】
[root@localhost lianxi]# crontab -e
第一步:按i进入计划任务的编辑模式,输入以下内容
0 23 * * * /root/lianxi/backup_log.sh
第二步:按Esc,输入:wq 退出并且保存
[root@localhost lianxi]# crontab -l 查看计划任务
0 23 * * * bash /root/lianxi/backup_log.sh
1.4.4 普通用户创建计划任务
1. lihua用户自己创建计划任务
[root@localhost cron]# su - lihua
上一次登录:三 3月 16 21:55:16 CST 2022pts/0 上
[lihua@localhost ~]$ crontab -e
2. root用户帮助lihua用户创建计划任务
[root@localhost cron]# crontab -e -u lihua
1.4.5 练习
- 每隔一分钟新建一个文件夹,这个文件名里需要包含当前时间,精确到秒
- 新建的文件夹保存在/root/lianxi/sanchuang
- 脚本名字create_dir.sh
需求分析
- 编写脚本实现新建文件夹,名字里包含当前的时间,精确到秒==》mkdir 和 date +%Y%m%d%H%M%S
- 脚本名字create_dir.sh,存放在/root/lianxi/sanchuang
- 制定计划任务,实现每一分钟执行上面的create_dir.sh脚本
【答案】
时间格式==》*/1 * * * * bash /root/lianxi/sanchuang/create_dir.sh 或 * * * * * bash /root/lianxi/sanchuang/create_dir.sh
[root@localhost sanchuang]# vim create_dir.sh
[root@localhost sanchuang]# cat create_dir.sh
#!/bin/bash
#获得当前时间
ctime=