Cron 定时任务基础
# 编辑定时任务
crontab -e
# 格式:分 时 日 月 周 命令
0 3 * * * /root/backup.sh # 每天凌晨 3 点备份
*/5 * * * * /root/healthcheck.sh # 每 5 分钟健康检查
0 * * * * python3 /root/crawler.py # 每小时运行爬虫
# 查看当前定时任务
crontab -l
实用脚本示例:VPS 健康检查
#!/bin/bash
# healthcheck.sh — 检查服务是否存活
services=("nginx" "mysql" "docker")
for s in "${services[@]}"; do
if ! systemctl is-active --quiet $s; then
echo "$s is DOWN! Restarting..." | tee -a /var/log/health.log
systemctl restart $s
fi
done
# 磁盘使用率超过 90% 时告警
USAGE=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
if [ $USAGE -gt 90 ]; then
echo "Disk usage at ${USAGE}%!" | tee -a /var/log/health.log
fi
实用脚本示例:Python 定时爬虫
# crawler.py — 定时抓取数据
import requests
from datetime import datetime
url = "https://api.example.com/data"
data = requests.get(url).json()
with open(f"/data/snapshot-{datetime.now():%Y%m%d-%H%M}.json", "w") as f:
import json; json.dump(data, f)
日志管理
Cron 任务的输出默认会发邮件(需要配邮件服务)。更好的做法是重定向到日志文件:
0 * * * * python3 /root/crawler.py >> /var/log/crawler.log 2>&1