【自己写的.exe封装为Windows服务后开机自启动失败解决办法】

每天学习一点点

问题描述

项目介绍:python Flask apcheduler
使用pyinstaller -F 将项目打包为.exe文件。
注册为windows服务,公司一个墨西哥项目,系统为win7 X64。
开机自启动失败(某些项目是可以开机自启动的)
注册为服务的.bat文件内容

# install.bat
@echo.service begin....
@echo off
cd /d %~dp0
set b=%cd%
@sc query 你的服务名 > NUL
@if errorlevel 1060 goto notexist
@goto exist

:notexist
@echo %b%
@sc create你的服务名 binPath= "%b%\你的.exe文件名" displayname= "服务显示的名字"
@goto end

:exist
@net stop 你的服务名
@sc delete 你的服务名
@goto notexist

:end
@net start 你的服务名
@sc config 你的服务名 start= AUTO
@echo off
@echo.service success.....
@pause
# uninstall.bat
@echo.service begin....
@echo off
@sc query 你的服务名 > NUL
@if errorlevel 1060 goto notexist
@goto exist

:notexist
@goto end

:exist
@net stop 你的服务名
@sc delete 你的服务名
@goto notexist

:end
@echo off
@echo.service success.....
@pause

问题查找

具体问题没有机会测试。等测试结果出来再更新!
2022年8月4号,加班到5点的我终于找到了问题!!!
程序内是需要连接sqlserver数据库的,当开机后服务自动运行时,sqlserver服务可能还没运行,导致服务运行失败

解决办法

1.设置服务依存关系(未验证):
设置依存关系的步骤
2脚本启动(验证通过):
1.创建.bat启动脚本

# start_service.bat
TIMEOUT /T 120 /NOBREAK  #延迟启动120秒。/NOBREAK 代表着只有使用Ctrl+C才能跳过延迟时间,没有这一项代表着任意键跳过。
%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit cd /d "%~dp0"		# 使用管理员权限运行脚本
C:\xxx\xxx\xxx.exe start 	# 服务启动

2.创建开机启动vbs脚本

# startup.vbs
Set ws = WScript.CreateObject("WScript.Shell")        
ws.run "C:\xxx\xxx\xxx.bat",0		# 上面的.bat脚本的路径