systemctl set-property 是最常用、最稳妥的线上动态限频方式,无需重启服务且立即生效;通过 cpuquota 设置百分比硬配额(如 cpuquota=30%),并可搭配 cpuweight 调节竞争时的相对份额,设置后自动写入 /etc/systemd/system/.../10-cpuquota.conf。

直接用 systemctl set-property 设置 CPU 使用率上限,是最常用、最稳妥的线上动态限频方式,无需重启服务,立即生效(依赖 cgroup v1 或 v2)。关键不是“能不能”,而是“怎么设才真正起作用”。
确认服务当前状态和限制能力
先检查目标服务是否已由 systemd 托管且处于活跃状态:
-
systemctl is-active <strong><font color="green">your-service.service</font></strong>—— 应返回active -
systemctl show -p CPUAccounting <strong><font color="green">your-service.service</font></strong>—— 若为no,需先启用统计(非必需,但建议):sudo systemctl set-property <strong><font color="green">your-service.service</font></strong> CPUAccounting=yes - 确认系统使用 cgroup v2(RHEL 8+/CentOS 8+、Ubuntu 20.04+ 默认):
stat -fc %T /sys/fs/cgroup返回cgroup2fs即为 v2
设置 CPUQuota(推荐:百分比硬配额)
CPUQuota 是最直观的 CPU 时间封顶参数。值为百分数,表示每秒最多可占用的 CPU 时间比例(100% = 1 核,400% = 4 核):
- 限制为 30%(即平均不超过 0.3 核):
sudo systemctl set-property <strong><font color="green">your-service.service</font></strong> CPUQuota=30% - 限制为 200%(允许最多 2 核并发):
sudo systemctl set-property <strong><font color="green">your-service.service</font></strong> CPUQuota=200% - 若想彻底“压低优先级”,可设为
5%或更低,适用于后台批处理类服务
该操作会自动在 /etc/systemd/system/your-service.service.d/ 下生成一个 10-CPUQuota.conf 类似文件,内容为:
CPUQuota=30%
补充控制:搭配 CPUWeight 或 CPUShares(权重调节)
当多个服务竞争 CPU 时,CPUQuota 是硬上限,而 CPUWeight(v2)或 CPUShares(v1)决定“分不到上限时怎么分”。默认值都是 1024:
- 让某服务在资源紧张时获得更多份额:
sudo systemctl set-property <strong><font color="green">your-service.service</font></strong> CPUWeight=2000 - 降低其调度权重(更“谦让”):
sudo systemctl set-property <strong><font color="green">your-service.service</font></strong> CPUWeight=512 - 注意:
CPUWeight和CPUQuota可共存,前者管“相对比例”,后者管“绝对上限”
验证与观察效果
设置后无需 reload 或 restart,几秒内即生效:
- 查看当前实际配额:
systemctl show -p CPUQuota <strong><font color="green">your-service.service</font></strong> - 实时观察 CPU 使用是否被压制:
systemctl status <strong><font color="green">your-service.service</font></strong>(看 “CPU usage” 行)
或用systemd-cgtop查看所有 cgroup 的实时 CPU 消耗 - 长期监控建议配合:
systemctl show -p CPUUsageNS <strong><font color="green">your-service.service</font></strong>(纳秒级累计值,可用于趋势分析)











