温馨提示×

如何定时centos cleanup任务

小樊
42
2026-10-03 03:11:20
栏目: 智能运维

在 CentOS 上定时执行 cleanup(清理)任务,通常有两种主流方式:cron(最常用) 和 systemd timer。下面按常见场景给你讲清楚。


一、使用 cron 定时清理(推荐入门)

1. 编写 cleanup 脚本

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

2. 添加到 crontab

crontab -e

每天凌晨 2 点执行:

0 2 * * * /root/cleanup.sh

查看已配置任务:

crontab -l

✅ 适合:简单脚本、传统服务器


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

1. 创建 cleanup 服务

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=Daily cleanup timer

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

[Install]
WantedBy=timers.target

3. 启用并启动

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

查看状态:

systemctl list-timers

✅ 适合:生产环境、可管理、可日志追踪


三、常见 cleanup 内容建议

  • /tmp、/var/tmp
  • journalctl --vacuum-size=500M
  • docker system prune(若用 Docker)
  • 删除旧日志 /var/log/*.log

四、调试建议

  • 脚本开头加:
exec >> /var/log/cleanup.log 2>&1
  • cron 环境可能缺少 PATH,脚本里用绝对路径

如果你能告诉我:

  • CentOS 版本(7 / 8 / Stream)
  • 想清理什么(日志 / 磁盘 / Docker)

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

0 踩