在 CentOS 上做 定时 cleanup(清理),通常有三种常见方式:cron / crontab、systemd timer、以及写脚本 + 定时任务。下面按常用程度给你说明。
例如清理 /tmp 和日志:
vi /root/cleanup.sh
内容示例:
#!/bin/bash
# 清理 /tmp 下 7 天前的文件
find /tmp -type f -mtime +7 -delete
# 清理日志
journalctl --vacuum-time=7d
# 清理 yum 缓存
yum clean all
赋予执行权限:
chmod +x /root/cleanup.sh
crontab -e
每天凌晨 2 点执行:
0 2 * * * /root/cleanup.sh >> /var/log/cleanup.log 2>&1
查看任务:
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=Run cleanup daily
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
systemctl daemon-reload
systemctl enable cleanup.timer
systemctl start cleanup.timer
查看状态:
systemctl list-timers
# 删除旧日志
find /var/log -type f -name "*.log" -mtime +30 -delete
# 清理 docker(如已安装)
docker system prune -af
# 清理内存缓存(谨慎)
sync; echo 3 > /proc/sys/vm/drop_caches
如果你能说明:
我可以给你更精确的定时清理方案。