Linux服务 - 01 定时任务
一、定时任务概述
目标:熟练书写定时任务规则,实现定时/重复执行指令/脚本
应用场景:定时任务+脚本备份,日常操作
定时任务:Linux闹钟,在指定的(日期、时间)指定任务,重复性,经常的任务交给定时任务
二、定时任务使用
2.1 服务与配置
01 服务
软件包:cronie
yum provides crond
cronie-1.4.11-23.el7.x86_64
服务名:crond
# 系统默认就运行的服务,并且是开机启动
# 查看运行状态,active 表示运行
# d 表示 daemon 守护进程
[root@python-server ~]# systemctl status crond
● crond.service - Command Scheduler
Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)
Active: `active (running)`since Wed 2023-04-19 18:17:45 CST; 2 days ago
Main PID: 663 (crond)
CGroup: /system.slice/crond.service
└─663 /usr/sbin/crond -n
Apr 19 18:17:45 python-server systemd[1]: Started Command Scheduler.
Apr 19 18:17:45 python-server crond[663]: (CRON) INFO (RANDOM_DELAY will be scaled with factor 33% if used.)
Apr 19 18:17:45 python-server crond[663]: (CRON) INFO (running with inotify support)
日志文件:
tail -f /var/log/corn
02 配置
配置文件存放目录:
# 默认是空的,如果有定时任务下面以用户名命名
/var/spool/cron
核心配置文件
定时任务配置文件 | |
---|---|
用户定时任务 | |
/var/spool/cron/root | root用户的定时任务是以root命名的配置文件 |
系统定时任务 | |
/etc/cron.d | |
/etc/cron.daily | 每天运行(系统运行) |
/etc/cron.deny | 拒绝哪些用户使用定时任务 |
/etc/cron.hourly | 每小时运行 |
/etc/cron.monthly | 每月运行 |
/etc/crontab | 定时任务配置文件(很少用) |
/etc/cron.weekly | 每周运行 |
03 命令
crontab
命令参数 | 功能描述 |
---|---|
-e | 编辑定时任务 ==> vim /var/spool/cront/用户名(root) |
-l | 查看列出定时任务 ==> cat /var/spool/cront/root |
-r | 清空定时任务,不提示(慎用) |
2.2 格式
- 按照行为单位进行配置(1行是1个定时任务)
- 每个定时任务分为两大部分**
什么时间
做什么
** - 什么时间:* * * * * 分、时、日、月、周
- 做什么:命令/脚本
# 格式
# 什么时间做什么
# 什么时间 做什么
* * * * * 命令或者脚本
2.3 示例
01 每天早上8:30去学校
30 08 * * * go to school
02 每天晚上12点上床睡觉
00 00 * * * go to bed
# 如果不加分钟处的00,是* 表示0-59,每个凌晨12点的每分钟都执行一次
2.4 定时任务时间其他格式
定时任务特殊符号 | |
---|---|
* | 所有,全部,在分钟上代表每分钟,在小时上代表每小时 |
/ | 每隔多久运行1次,*/2 * * * * 每2分钟执行一次 |
- | 从哪里来到哪里去,时间范围 00 09-12 * * * 每天9到12点每个小时执行一次 |
, 逗号 | 独立,互不想干的时间。00 00,07,14 * * * 每天半夜12点,上午7点,下午14点执行一次 |
2.5 案例
定时任务书写流程:
1.根据题目选择命令,测试命令/脚本
2.对应的命令写入到定时任务配置文件中(crontab -e)
3.等待运行与检查结果,查看定时任务日志(/var/log/cron)
01 每分钟输出 hello world追加到/tmp/hello.txt中
* * * * * echo "hello world" >> /tmp/hello.txt
02 每2分钟同步系统的时间ntpdate
*/2 * * * * /usr/sbin/ntpdate ntpdate ntp1.aliyun.com