Files
nexus/wiki/concepts/Cron定时任务.md
2026-04-22 04:03:04 +08:00

99 lines
2.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
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.
---
title: "Cron定时任务"
tags: [linux, automation, devops, ubuntu]
date: 2026-04-26
---
# Cron定时任务 (Cron Job)
## Definition
Cron 是 Linux/Unix 系统的定时任务调度器允许用户配置在指定时间自动执行命令或脚本。Cron 通过 crontabcron table配置文件管理所有定时任务。
## Basic Format
```
┌───────────── 分钟 (0-59)
│ ┌───────────── 小时 (0-23)
│ │ ┌───────────── 日期 (1-31)
│ │ │ ┌───────────── 月份 (1-12)
│ │ │ │ ┌───────────── 星期 (0-7, 0和7都是周日)
│ │ │ │ │
* * * * * command
```
## Examples
### 每日凌晨3点执行备份
```
0 3 * * * /usr/local/bin/rsync_backup.sh
```
### 每6小时执行一次
```
0 */6 * * * /path/to/script.sh
```
### 每周日凌晨2点执行
```
0 2 * * 0 /path/to/weekly_backup.sh
```
### 每月的第一天凌晨4点执行
```
0 4 1 * * /path/to/monthly_backup.sh
```
## Crontab Commands
```bash
# 编辑当前用户的 crontab
crontab -e
# 查看当前用户的 crontab
crontab -l
# 删除当前用户的 crontab
crontab -r
# 以 root 身份编辑系统 crontab
sudo crontab -e
```
## Best Practices for Backup Jobs
### 1. 使用绝对路径
Cron 任务的执行环境与交互式 shell 不同PATH 环境变量可能不完整:
```bash
0 3 * * * /usr/local/bin/rsync_backup.sh # ✅ 使用绝对路径
```
### 2. 使用 nohup 确保后台运行
```bash
0 3 * * * sudo nohup /usr/local/bin/rsync_backup.sh > /dev/null 2>&1 &
```
### 3. 使用锁文件防止重复执行
```bash
LOCKFILE="/tmp/rsync_backup.lock"
if [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then
echo "备份任务已在运行中,跳过本次执行。"
exit
fi
echo $$ > ${LOCKFILE}
```
### 4. 日志记录
```bash
LOG="/var/log/rsync_backup.log"
echo "--- 开始备份: $(date) ---" >> "$LOG"
rsync -azR ... >> "$LOG" 2>&1
```
## Related Concepts
- [[增量备份]] — Cron 定时任务自动执行增量备份
- [[进程管理]] — 后台进程的控制与监控
- [[挂载点检查]] — 备份前的安全检查
- [[永久挂载]] — 确保 Cron 任务执行时存储可用
## See Also
- [[Disaster-Recovery]] — Cron 任务实现自动化的灾备恢复点
- [[RTO]] — Cron 任务频率影响恢复时间目标