教程 |Windows使用WinSW实现开机自启动服务
实用教程 |开机自启 | WinSW
标签:服务项自启、shell命令启动
在windwos系统中,有时候需要 nginx的开机自启动,或者java的jar开机自启动,或者内网穿透工具(frp)的开机自启动,使用winsw将shell命令包成服务并设置开机自启动。
Windows Service Wrapper是一个可执行二进制文件,可用于包装和管理作为Windows服务的自定义进程,下载安装包后,您可以将 WinSW.exe 重命名为任何名称,例如 MyService.exe 。接下来您可以创建Myservice.xml文件进行服务配置。最后 MyService.exe install安装到服务即可。
WinSW开源和下载地址(最新版WinSW v2.12.0)
地址:https://github.com/winsw/winsw/releases/tag/v2.11.0
我的电脑是win10的64位系统,因此下载对应的版本,WinSW需要win10系统.NET Framework支持的,在老系统中,可能需要弄兼容。
1.windows10系统配置nginx开机启动
Nginx-WinSW-x64.xml和Nginx-WinSW-x64.exe名称必须保持一致,使用的相对路径
Nginx-WinSW-x64.xml文件内容
<service>
<!--安装windows服务后的服务ID,必须是唯一的--><id>Nginx-Service</id>
<!--服务名称,唯一的,一般和id一致即可--><name>Nginx-Service</name>
<!--该服务的描述--> <description>Nginx-Service-Test</description>
<!--启动 执行的命令--><executable>nginx.exe</executable>
<!--停止--><stopexecutable>nginx.exe -s stop</stopexecutable>
<!--第一次启动失败120秒重启--><onfailure action="restart" delay="120 sec"/>
<!--第二次启动失败300秒后重启计算机--><onfailure action="reboot" delay="300 sec"/>
<!--开机启动--><startmode>Automatic</startmode>
<!--日志配置--><logpath>nginx-WinSW-log</logpath>
<!--append:追加模式;reset:重设模式,每次服务启动时,旧的日志文件都会被截断;none:不生成任何日志文件 --><logmode>none</logmode>
</service>
nginx-winsw-install.bat
@echo offNginx-WinSW-x64.exe installexit
nginx-winsw-start.bat
@echo offNginx-WinSW-x64.exe startexit
nginx-winsw-stop.bat
@echo offNginx-WinSW-x64.exe stopexit
nginx-winsw-uninstall.bat
@echo offNginx-WinSW-x64.exe uninstallexit
首先运行nginx-winsw-install.bat 这样便能达到开机启动的作用,
如果马上要启动,那么在注册运行之后运行nginx-winsw-start.bat
停止和注销注册也有,注销之后开机启动就不起作用了
2.window10配置java开机启动(系统需要有java环境)
Boot-WinSW-x64.xml
<service>
<!-- 该服务的唯一标识 --><id>boot-black</id>
<!-- 该服务的名称 --><name>boot-black-0.0.1</name>
<!-- 该服务的描述 --><description>boot-black-0.0.1-SNAPSHOT</description>
<!-- 要运行的程序路径 --><executable>java</executable>
<!-- 携带的参数 --><arguments>-jar boot-black-0.0.1-SNAPSHOT.jar</arguments>
<!-- 第一次启动失败 60秒重启 --><onfailure action="restart" delay="120 sec"/>
<!-- 第二次启动失败 120秒后重启 --><onfailure action="restart" delay="240 sec"/>
<!-- 日志模式 --><logmode>append</logmode>
<!-- 指定日志文件目录(相对于executable配置的路径) --><logpath>boot-WinSW-log</logpath><!-- append:追加模式;reset:重设模式,每次服务启动时,旧的日志文件都会被截断;none:不生成任何日志文件 --><logmode>none</logmode>
</service>
boot-black-install.bat
@echo offBoot-WinSW-x64.exe installexit
boot-black-uninstall.bat
@echo offBoot-WinSW-x64.exe uninstallexit
可以参照对比写出相应的bat操作文件
@echo offBoot-WinSW-x64.exe startexit@echo offBoot-WinSW-x64.exe stopexit
3.window10配置frp开机启动
下载后将winsw.exe(WinSW-x64.exe 重命名后的名称为winsw.exe)放在和frp同级目录
新建xml文件命名为winsw.xml,进行配置,如下:
<service>
<id>frpc</id>
<name>frpc</name>
<description>frpc服务</description>
<executable>frpc</executable>
<arguments>-c frpc.ini</arguments>
<logmode>reset</logmode>
</service>
文件结构如下图所示
运行命令:
# 安装服务
winsw.exe install
# 卸载服务
winsw.exe uninstall
从而实现程序作为开机启动项。