温馨提示×

如何定时linux cleanup

小樊
41
2026-09-29 13:18:43
栏目: 智能运维

在 Linux 上“定时执行 cleanup(清理任务)”通常有几种常见做法,下面按使用场景给你总结。


一、使用 cron(最常用)

1️⃣ 编辑当前用户的定时任务

crontab -e

2️⃣ 示例:每天凌晨 3 点清理 /tmp

0 3 * * * /usr/bin/find /tmp -type f -mtime +7 -delete

含义:

  • 0 3 * * *:每天 03:00
  • 删除 /tmp 中 7 天前的文件

3️⃣ 示例:每周清理日志

0 4 * * 0 /usr/bin/find /var/log -name "*.log" -mtime +30 -delete

二、使用 systemd timer(现代 Linux 推荐)

适合服务器、容器、生产环境。

1️⃣ 创建 cleanup 脚本

sudo vim /usr/local/bin/cleanup.sh

内容示例:

#!/bin/bash
find /tmp -type f -mtime +7 -delete
journalctl --vacuum-time=7d
chmod +x /usr/local/bin/cleanup.sh

2️⃣ 创建 service

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

[Service]
Type=oneshot
ExecStart=/usr/local/bin/cleanup.sh

3️⃣ 创建 timer

sudo vim /etc/systemd/system/cleanup.timer
[Unit]
Description=Daily Cleanup

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

4️⃣ 启用

sudo systemctl enable --now cleanup.timer

查看状态:

systemctl list-timers

三、清理常见内容示例

清理 Docker

docker system prune -af

清理 journal 日志

journalctl --vacuum-time=7d

清理 apt 缓存(Debian/Ubuntu)

apt-get clean

清理 yum / dnf 缓存

dnf clean all

四、安全建议 ⚠️

  • 先用 find ... -print 测试
  • 避免 -delete 直接删根目录
  • 重要数据先备份
  • 日志记录:
>> /var/log/cleanup.log 2>&1

如果你能告诉我:

  • 是 桌面 / 服务器 / 容器
  • 想清理 什么(日志 / 临时文件 / Docker / 缓存)

我可以给你一份可直接用的定时清理脚本。

0 踩