Ubuntu 定时器设置超时时间的实用方法
一、使用 systemd 定时器设置任务最大执行时长
[Unit]
Description=My timed job
[Service]
ExecStart=/usr/local/bin/myjob.sh
TimeoutSec=300 # 最大运行 300 秒(5 分钟)
Restart=on-failure
[Unit]
Description=Run myjob hourly
[Timer]
OnCalendar=hourly
Persistent=true
Unit=myjob.service
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now myjob.timer
systemctl list-timers --all
systemctl status myjob.timer
journalctl -u myjob.service
说明:上述做法适用于 Ubuntu 16.04+(使用 systemd)。TimeoutSec 既可在 [Service] 中设置全局超时,也可在 [Timer] 中使用如 TimeoutStartSec=…、TimeoutStopSec=… 分别控制启动/停止阶段的最大等待时间。二、使用 crontab 时的超时控制
#!/usr/bin/env bash
set -e
timeout 300 /usr/local/bin/myjob.sh
然后用 crontab 定时执行这个包装器:# 每 5 分钟执行一次
*/5 * * * * /usr/local/bin/run_with_timeout.sh
说明:crontab 适合做“何时运行”的调度;若需“运行多久后强制结束”,请选择 systemd 方案或在脚本中用 timeout 等工具实现。三、在程序内设置定时器与超时(C/POSIX 场景)
四、实用建议