Ubuntu 定时器设置超时时间的实用方法

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