在 Ubuntu 系统中,你可以使用 systemd 的定时器(timer)来实现超时功能。以下是设置定时器超时的步骤:
my-service.service),这个服务文件定义了你想要执行的操作。将此文件保存在 /etc/systemd/system/ 目录下。[Unit]
Description=My custom service
[Service]
ExecStart=/path/to/your/script.sh
my-service.timer),这个文件定义了定时器的行为。将此文件保存在 /etc/systemd/system/ 目录下。[Unit]
Description=Run my-service.service every hour
[Timer]
OnCalendar=*-*-* *:00:00
Persistent=true
Unit=my-service.service
[Install]
WantedBy=timers.target
在这个例子中,OnCalendar 行定义了定时器的触发时间。这里设置为每小时执行一次。你可以根据需要修改这个值。
systemd 配置:sudo systemctl daemon-reload
sudo systemctl enable --now my-service.timer
sudo systemctl list-timers --all
要设置超时,你可以在你的脚本(例如:/path/to/your/script.sh)中使用 timeout 命令。例如,如果你想要在脚本运行超过 30 分钟时终止它,可以在脚本中添加以下内容:
timeout 30m /path/to/your/command
这将在 30 分钟后终止 /path/to/your/command。如果你想要在脚本超时时收到通知,可以使用 --signal 选项发送一个信号(例如,SIGUSR1):
timeout --signal=SIGUSR1 30m /path/to/your/command
然后,你可以在脚本中捕获这个信号并执行相应的操作。