温馨提示×

能否定时linux cleanup

小樊
34
2026-09-23 17:32:58
栏目: 智能运维

可以的,在 Linux 上“定时做 cleanup(清理)”通常有三种常见做法,取决于你想清理什么、以及系统类型。


一、用 cron 定时清理(最常用)

1. 编辑定时任务

crontab -e

2. 示例:每天凌晨 3 点清理

0 3 * * * /home/user/cleanup.sh >> /var/log/cleanup.log 2>&1

3. 常见 cleanup 脚本示例

#!/bin/bash
# 清理临时文件
rm -rf /tmp/*
rm -rf /var/tmp/*

# 清理旧日志(保留 7 天)
find /var/log -type f -name "*.log" -mtime +7 -delete

# 清理 apt 缓存(Debian/Ubuntu)
apt-get clean

# 清理 yum 缓存(CentOS/RHEL)
yum clean all
chmod +x cleanup.sh

二、用 systemd timer(更现代)

1. 创建 service

/etc/systemd/system/cleanup.service

[Unit]
Description=Cleanup Job

[Service]
Type=oneshot
ExecStart=/home/user/cleanup.sh

2. 创建 timer

/etc/systemd/system/cleanup.timer

[Unit]
Description=Daily Cleanup

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

3. 启用

systemctl enable --now cleanup.timer

三、利用系统自带清理机制

1. 日志自动清理(systemd)

journalctl --vacuum-time=7d

2. 临时文件自动清理

systemd-tmpfiles --clean

四、常见清理对象建议

  • /tmp, /var/tmp
  • 日志文件
  • 软件包缓存
  • Docker 镜像(如 docker system prune)
  • 用户下载/临时目录

如果你能告诉我:

  • 使用的 Linux 发行版
  • 想清理的具体内容(日志 / 容器 / 缓存 / 磁盘)

我可以帮你写一份精准的定时清理方案。

0 踩