- 创建 svc.sh文件
- 赋予权限 chmod +x ./svc.sh
-
如果需要延迟执行,修改Service
ExecStartPre=/bin/sleep 6 # 延迟6秒执行
#!/bin/bash
# 需要启动脚本的位置
SCRIPT_PATH="/data/app/ai-qa/java.sh"
# 服务名称
SERVICE_NAME="ai-qa"
# 添加到开机启动
add_to_startup() {
if [ ! -f "/etc/systemd/system/$SERVICE_NAME.service" ]; then
echo "[Unit]
Description=My Startup Service
[Service]
ExecStartPre=/bin/sleep 6
ExecStart=$SCRIPT_PATH
Restart=always
[Install]
WantedBy=multi-user.target" | sudo tee /etc/systemd/system/$SERVICE_NAME.service
echo "服务已添加到开机启动"
else
echo "服务已存在,无需重复添加"
fi
sudo systemctl enable $SERVICE_NAME
}
# 移除开机启动
remove_from_startup() {
if [ -f "/etc/systemd/system/$SERVICE_NAME.service" ]; then
sudo systemctl disable $SERVICE_NAME
sudo rm /etc/systemd/system/$SERVICE_NAME.service
echo "服务已从开机启动中移除"
else
echo "服务不存在,无需移除"
fi
}
# 启动服务
start_service() {
echo "将在 30 秒后启动服务: $SERVICE_NAME"
sleep 30
sudo systemctl start $SERVICE_NAME
echo "服务已启动: $SERVICE_NAME"
}
# 停止服务
stop_service() {
sudo systemctl stop $SERVICE_NAME
echo "服务已停止: $SERVICE_NAME"
}
# 主程序
case $1 in
add)
add_to_startup
;;
remove)
remove_from_startup
;;
start)
start_service
;;
stop)
stop_service
;;
*)
echo "用法: $0 {add|remove|start|stop}"
exit 1
;;
esac
文章评论