在 CentOS 中让“清理(cleanup)”自动执行,常见做法有 cron 定时任务、systemd timer、日志轮转+自动清理 等。下面按使用场景给你一套实用方案。
例如:/opt/scripts/cleanup.sh
#!/bin/bash
# 清理 yum 缓存
yum clean all
# 删除 /tmp 下 7 天未访问的文件
find /tmp -type f -atime +7 -delete
# 清理 journal 日志(保留最近 3 天)
journalctl --vacuum-time=3d
# 删除旧的核心转储
find /var/crash -type f -mtime +7 -delete
赋予执行权限:
chmod +x /opt/scripts/cleanup.sh
crontab -e
示例(每天凌晨 2 点执行):
0 2 * * * /opt/scripts/cleanup.sh >> /var/log/cleanup.log 2>&1
/etc/systemd/system/cleanup.service
[Unit]
Description=CentOS Cleanup
[Service]
Type=oneshot
ExecStart=/opt/scripts/cleanup.sh
/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 --now cleanup.timer
查看状态:
systemctl list-timers
编辑:
/etc/logrotate.conf
示例:
/var/log/myapp/*.log {
daily
rotate 7
compress
missingok
notifempty
}
手动测试:
logrotate -d /etc/logrotate.conf
docker system prune -af
可加入 cron:
0 3 * * * docker system prune -af
/tmp、/var/tmpyum cachejournalctlpackage-cleanup --oldkernels --count=2
如果你能说明具体想清理什么(磁盘 / 日志 / 缓存 / Docker / 定时任务),我可以直接给你一份可复制的脚本和配置。