温馨提示×

centos cpustat如何定时

小樊
43
2026-09-12 02:55:17
栏目: 智能运维

在 CentOS 上如果你想定时使用 cpustat 收集 CPU 使用情况,常见有几种方式,下面按使用场景给你说明。


一、先确认 cpustat 是否安装

cpustat 通常来自 sysstat 包:

which cpustat

如果没有:

yum install sysstat -y

CentOS 7/8 通用


二、方式一:用 cron 定时执行(最常用)

1️⃣ 编辑定时任务

crontab -e

2️⃣ 示例:每 5 分钟记录一次 CPU 状态

*/5 * * * * /usr/bin/cpustat >> /var/log/cpustat.log 2>&1

3️⃣ 示例:每隔 10 秒采一次(cron 最小单位是分钟)

cron 不支持秒级,可用 sleep 变通:

* * * * * for i in 1 2 3 4 5 6; do /usr/bin/cpustat >> /var/log/cpustat.log; sleep 10; done

三、方式二:用 watch 临时实时监控(非记录)

适合临时看:

watch -n 5 cpustat

每 5 秒刷新一次(不写文件)


四、方式三:用 systemd timer(CentOS 7+ 推荐)

1️⃣ 创建 service

vi /etc/systemd/system/cpustat.service
[Unit]
Description=cpustat logging

[Service]
ExecStart=/usr/bin/cpustat >> /var/log/cpustat.log

2️⃣ 创建 timer

vi /etc/systemd/system/cpustat.timer
[Unit]
Description=Run cpustat every 5 minutes

[Timer]
OnCalendar=*:0/5
Persistent=true

[Install]
WantedBy=timers.target

3️⃣ 启用

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

五、常见参数示例

cpustat 1 5
  • 1:间隔 1 秒
  • 5:采样 5 次

六、日志查看

tail -f /var/log/cpustat.log

如果你能告诉我:

  • CentOS 版本(7 / 8 / Stream)
  • 是想 实时监控 还是 长期记录日志
  • 采样频率要求(秒 / 分钟)

我可以给你更精确的配置。

0