在 Debian 上“定时跑 cpustat”通常有几种做法,取决于你是想周期性采集、写日志还是做监控。下面按常见场景给你几种方案。
cpustat 通常来自 sysstat 包:
sudo apt update
sudo apt install sysstat
验证:
which cpustat
cpustat 1 5
编辑当前用户的 cron:
crontab -e
添加:
* * * * * /usr/bin/cpustat 1 1 >> /var/log/cpustat.log 2>&1
含义:
*/5 * * * * /usr/bin/cpustat 5 1 >> /var/log/cpustat.log 2>&1
*/5 * * * * echo "=== $(date) ===" >> /var/log/cpustat.log; /usr/bin/cpustat 5 1 >> /var/log/cpustat.log
sudo tee /etc/systemd/system/cpustat.service > /dev/null <<'EOF'
[Unit]
Description=Run cpustat
[Service]
Type=oneshot
ExecStart=/usr/bin/cpustat 5 1 >> /var/log/cpustat.log
EOF
sudo tee /etc/systemd/system/cpustat.timer > /dev/null <<'EOF'
[Unit]
Description=Timer for cpustat
[Timer]
OnCalendar=*:0/5
Persistent=true
[Install]
WantedBy=timers.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now cpustat.timer
查看状态:
systemctl list-timers | grep cpustat
你其实不一定需要 cpustat,可以用:
sar 1 0
或
mpstat 1
它们更适合长期监控。
sudo tee /etc/logrotate.d/cpustat > /dev/null <<'EOF'
/var/log/cpustat.log {
weekly
rotate 4
compress
missingok
notifempty
}
EOF
| 需求 | 推荐方式 |
|---|---|
| 简单定时采集 | cron |
| 系统级、可控 | systemd timer |
| 长期监控 | sar / mpstat |
| 写日志分析 | cron + logrotate |
如果你能告诉我:
我可以帮你写一套更完整的方案。