linux/计划任务.md
2025-03-17 13:40:43 +08:00

101 lines
2.7 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<h2><center>计划任务</center></h2>
------
## 一:简介
在 Linux 系统中,计划任务用于自动化执行周期性或定时任务(如备份、日志清理、系统监控等)。主要通过 cron 和 at 工具实现。
## 二cron 服务(周期性任务)
### 1. 介绍
cron 是 Linux 的守护进程,用于按固定周期(分钟、小时、天等)执行任务。
### 2. 管理 cron 任务
- 用户级任务:每个用户有自己的 crontab 文件。
```bash
# 编辑当前用户的 cron 任务(保存后自动生效)
[root@wxin ~]# crontab -e
# 查看当前用户的 cron 任务
[root@wxin ~]# crontab -l
# 删除当前用户的所有 cron 任务
[root@wxin ~]# crontab -r
```
- 系统级任务:编辑 /etc/crontab 或添加脚本到以下目录:
1. /etc/cron.hourly/:每小时执行
2. /etc/cron.daily/:每天执行
3. /etc/cron.weekly/:每周执行
4. /etc/cron.monthly/:每月执行
### 3. crontab 语法格式
```shell
* * * * * <命令或脚本>
│ │ │ │ │
│ │ │ │ └─ 星期几0-70 和 7 均为周日)
│ │ │ └─── 月份1-12
│ │ └───── 日1-31
│ └─────── 小时0-23
└───────── 分钟0-59
```
实例:
```shell
# 每天凌晨 3 点执行备份脚本
0 3 * * * /root/backup.sh
# 每 10 分钟检查一次系统状态
*/10 * * * * /usr/bin/monitor.sh
# 每周一和周五的下午 5:30 清理日志
30 17 * * 1,5 /usr/bin/clean_logs.sh
# 每小时的第 5 分钟和第 35 分钟发送通知
5,35 * * * * /usr/bin/send-alert
```
符号:
| 符号 | 说明 | 示例 |
| :--: | :------------: | :------------------------------------------: |
| * | 所有可能值 | * * * * * ----> 每分钟 |
| , | 指定多个时间点 | 0,15,30 * * * * -----> 每小时的01530分钟 |
| - | 时间范围 | 0 9-18 * * * -----> 每天9点到18点整点执行 |
| /n | 间隔频率 | */5 * * * * -----> 每5分钟 |
## 三at 命令(一次性任务)
### 1. 介绍
at 用于在指定时间执行一次性任务如2小时后重启服务
### 2. 基本用法
```bash
# 创建一个任务(按 Ctrl+D 结束输入)
at 15:30 2024-10-01
at> /path/to/script.sh
at> <EOT>
# 查看未执行的 at 任务
atq
# 删除任务ID 通过 atq 获取)
atrm <任务ID>
```
### 3. 时间格式示例
```bash
at now + 2 hours # 2 小时后执行
at 3:30 tomorrow # 明天 3:30 执行
at 10:00 Oct 1 # 10 月 1 日 10 点执行
```