本文目录导读:

Linux Crontab 定时任务(最常用)
基本用法
# 编辑定时任务 crontab -e # 每天凌晨2点清理日志 0 2 * * * /usr/bin/find /var/log -name "*.log" -mtime +7 -delete # 每30分钟清理一次临时文件 */30 * * * * /opt/scripts/cleanup.sh >> /var/log/cleanup.log 2>&1
清理脚本示例
#!/bin/bash
# cleanup.sh
# 清理7天前的日志文件
find /var/log/app -name "*.log" -mtime +7 -delete
# 清理10天前的备份文件
find /backup -name "*.tar.gz" -mtime +10 -delete
# 清理空目录
find /tmp -type d -empty -delete
# 限制文件大小(超过100MB的日志做切割)
find /var/log -size +100M -exec gzip {} \;
echo "Cleanup completed at $(date)"
Windows 任务计划程序
PowerShell 清理脚本
# cleanup.ps1
$days = 7
$path = "C:\logs"
# 删除7天前的文件
Get-ChildItem -Path $path -Recurse |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$days) } |
Remove-Item -Force
# 记录日志
Write-Output "Cleanup completed at $(Get-Date)" | Out-File -Append C:\logs\cleanup.log
创建定时任务(管理员权限)
# 创建每天凌晨2点执行的任务 $action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\scripts\cleanup.ps1" $trigger = New-ScheduledTaskTrigger -Daily -At 02:00am $principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount Register-ScheduledTask -TaskName "LogCleanup" -Action $action -Trigger $trigger -Principal $principal
Docker 容器定时清理
使用 Docker 自带的清理命令
# 添加定时任务(宿主机) # 每天凌晨3点清理未使用的容器和镜像 0 3 * * * docker system prune -af --volumes >> /var/log/docker-cleanup.log 2>&1
Docker Compose + Cron 容器方案
# docker-compose.yml
version: '3.8'
services:
cron-cleanup:
image: alpine:latest
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./cleanup.sh:/cleanup.sh
command: |
sh -c "
echo '0 3 * * * sh /cleanup.sh' > /etc/crontabs/root
crond -f
"
Python 脚本 + schedule 库
# cleanup_scheduler.py
import schedule
import time
import shutil
from pathlib import Path
import logging
logging.basicConfig(level=logging.INFO)
def cleanup_logs():
"""清理日志文件"""
log_dir = Path("/var/log/app")
if log_dir.exists():
for f in log_dir.glob("*.log"):
if f.stat().st_mtime < time.time() - 7 * 86400:
f.unlink()
logging.info(f"Deleted: {f}")
def cleanup_temp():
"""清理临时文件"""
temp_dir = Path("/tmp")
if temp_dir.exists():
for item in temp_dir.iterdir():
if item.is_file() and item.stat().st_mtime < time.time() - 24 * 3600:
item.unlink()
logging.info(f"Deleted temp: {item}")
# 设置定时任务
schedule.every().day.at("02:00").do(cleanup_logs)
schedule.every(30).minutes.do(cleanup_temp)
# 运行
while True:
schedule.run_pending()
time.sleep(60)
复杂场景:带日志记录和通知
#!/bin/bash
# advanced_cleanup.sh
LOG_FILE="/var/log/cleanup/cleanup-$(date +%Y%m%d).log"
NOTIFY_EMAIL="admin@example.com"
# 创建日志目录
mkdir -p $(dirname $LOG_FILE)
# 记录开始
echo "[$(date)] Starting cleanup..." | tee -a $LOG_FILE
# 清理函数
cleanup_directory() {
local dir=$1
local days=$2
local pattern=$3
if [ -d "$dir" ]; then
local count=$(find "$dir" -name "$pattern" -mtime +$days | wc -l)
find "$dir" -name "$pattern" -mtime +$days -delete
echo "Cleaned $count files from $dir (older than $days days)" | tee -a $LOG_FILE
fi
}
# 执行清理
cleanup_directory "/var/log/app" 7 "*.log"
cleanup_directory "/tmp" 1 "*"
cleanup_directory "/backup/db" 30 "*.sql.gz"
# 检查磁盘空间
DISK_USAGE=$(df -h / | tail -1 | awk '{print $5}')
echo "Current disk usage: $DISK_USAGE" | tee -a $LOG_FILE
# 如果磁盘使用率超过80%,发送警告
if [ ${DISK_USAGE%\%} -gt 80 ]; then
echo "Warning: Disk usage is above 80%" | tee -a $LOG_FILE
mail -s "Disk Usage Warning" $NOTIFY_EMAIL < $LOG_FILE
fi
# 清理超过30天的清理日志
find /var/log/cleanup -name "*.log" -mtime +30 -delete
echo "[$(date)] Cleanup completed" | tee -a $LOG_FILE
最佳实践建议
- 日志记录:始终保留清理操作的日志
- 测试执行:先使用
-print而不是-delete测试 - 错误处理:添加错误处理和告警机制
- 权限控制:使用最小必要权限运行
- 性能考虑:避免在高峰时段执行大量I/O操作
选择哪种方式取决于你的具体环境(Linux/Windows/容器化)和需求复杂度。