温馨提示×

centos cleanup怎样定时任务

小樊
48
2026-09-06 05:46:35
栏目: 智能运维

在 CentOS 中,“cleanup(清理)”通常可以通过 定时任务(cron) 来定期执行,比如清理日志、缓存、临时文件等。下面按常见场景给你说明。


一、使用 cron 定时执行清理任务(最常用)

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

crontab -e

2. 添加清理任务示例

每天凌晨 2 点清理 /tmp 下 7 天前的文件

0 2 * * * find /tmp -type f -mtime +7 -delete

每周日清理 yum 缓存

0 3 * * 0 yum clean all

每天清理 journal 日志(保留最近 7 天)

0 1 * * * journalctl --vacuum-time=7d

二、使用系统级 cron(推荐服务器使用)

1. 编写清理脚本

vi /usr/local/bin/cleanup.sh

示例内容:

#!/bin/bash
find /tmp -type f -mtime +7 -delete
journalctl --vacuum-time=7d
yum clean all

赋予执行权限:

chmod +x /usr/local/bin/cleanup.sh

2. 加到系统 crontab

vi /etc/crontab

添加:

0 2 * * * root /usr/local/bin/cleanup.sh

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

1. 创建 service

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

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

2. 创建 timer

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

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

3. 启用

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

四、常见清理对象建议

  • /tmp/var/tmp
  • /var/log
  • journalctl
  • yum/dnf 缓存
  • Docker:
docker system prune -f

如果你说的 “centos cleanup” 是指某个具体工具(如 package-cleanupdnf autoremove、磁盘清理脚本),可以告诉我具体场景,我可以给你更精确的定时方案。

0