在 CentOS 上定时执行 cleanup(清理)任务,通常有两种主流方式:cron(最常用) 和 systemd timer。下面按常见场景给你讲清楚。
例如清理 /tmp 和日志:
vi /root/cleanup.sh
内容示例:
#!/bin/bash
# 清理7天前的/tmp文件
find /tmp -type f -mtime +7 -delete
# 清理系统日志(journal)
journalctl --vacuum-time=7d
# 清理yum缓存
yum clean all
赋予执行权限:
chmod +x /root/cleanup.sh
crontab -e
每天凌晨 2 点执行:
0 2 * * * /root/cleanup.sh
查看已配置任务:
crontab -l
✅ 适合:简单脚本、传统服务器
vi /etc/systemd/system/cleanup.service
[Unit]
Description=Cleanup task
[Service]
Type=oneshot
ExecStart=/root/cleanup.sh
vi /etc/systemd/system/cleanup.timer
[Unit]
Description=Daily cleanup timer
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
systemctl daemon-reload
systemctl enable --now cleanup.timer
查看状态:
systemctl list-timers
✅ 适合:生产环境、可管理、可日志追踪
/tmp、/var/tmpjournalctl --vacuum-size=500Mdocker system prune(若用 Docker)/var/log/*.logexec >> /var/log/cleanup.log 2>&1
如果你能告诉我:
我可以给你更精确的定时清理方案。