温馨提示×

centos cleanup如何定时

小樊
45
2026-09-27 06:14:57
栏目: 智能运维

在 CentOS 上做 定时 cleanup(清理),通常有三种常见方式:cron / crontab、systemd timer、以及写脚本 + 定时任务。下面按常用程度给你说明。


一、使用 crontab(最常用)

1. 编写清理脚本

例如清理 /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

2. 加入 crontab

crontab -e

每天凌晨 2 点执行:

0 2 * * * /root/cleanup.sh >> /var/log/cleanup.log 2>&1

查看任务:

crontab -l

二、使用 systemd timer(CentOS 7+ 推荐)

1. 创建 service

vi /etc/systemd/system/cleanup.service
[Unit]
Description=Cleanup Task

[Service]
Type=oneshot
ExecStart=/root/cleanup.sh

2. 创建 timer

vi /etc/systemd/system/cleanup.timer
[Unit]
Description=Run cleanup daily

[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true

[Install]
WantedBy=timers.target

3. 启用并启动

systemctl daemon-reload
systemctl enable cleanup.timer
systemctl start cleanup.timer

查看状态:

systemctl list-timers

三、常见 cleanup 项目参考

# 删除旧日志
find /var/log -type f -name "*.log" -mtime +30 -delete

# 清理 docker(如已安装)
docker system prune -af

# 清理内存缓存(谨慎)
sync; echo 3 > /proc/sys/vm/drop_caches

四、建议

  • 服务器环境:systemd timer 更稳妥
  • 简单任务:crontab 最方便
  • 一定要 重定向日志,方便排查问题

如果你能说明:

  • CentOS 版本(6 / 7 / 8 / Stream)
  • 想清理什么(日志 / 临时文件 / docker / 磁盘)

我可以给你更精确的定时清理方案。

0 踩