Ubuntu 定时器优先级设置指南

一、概念与范围
二、使用 cron 设置 CPU 调度优先级
crontab -e* * * * * nice -n -10 /usr/local/bin/backup.shnice -n -10 表示将进程的 nice 值设为 -10(需要更高权限;普通用户通常只能提高到 0,降低负数需要 sudo)。renice -5 -p $(pgrep backup.sh)(将 PID 为 backup.sh 的进程 nice 设为 -5)。ps -o pid,nice,cmd -C backup.sh。三、使用 systemd timer 设置调度及时性与服务优先级
[Unit]Description=My high-priority task[Service]Type=oneshotExecStart=/usr/local/bin/backup.shNice=-10IOSchedulingClass=realtimeIOSchedulingPriority=1Nice=-10 调整 CPU 调度优先级;IOSchedulingClass=realtime 与 IOSchedulingPriority=1 提升 I/O 调度优先级(需要 root 且谨慎使用)。[Unit]Description=Run mytask daily at 02:00[Timer]OnCalendar=*-*-* 02:00:00AccuracySec=1sPersistent=true[Install]WantedBy=timers.targetAccuracySec=1s 将唤醒精度设为 1 秒(更小更“准时”,但不提升 CPU 调度优先级)。sudo systemctl daemon-reloadsudo systemctl enable --now mytask.timersystemctl list-timersjournalctl -u mytask.service四、实用建议与注意事项
ps -o pid,nice,cmd 检查 nice 值;用 systemctl status/ journalctl 查看定时器与服务运行状态。