在windows下通過winsw將程序註冊爲服務實現開機自啓

前言

  1. 查看電腦 net framework 版本
    在命令行工具中運行:dir /b %windir%\Microsoft.NET\Framework\v* 可查看列表,最新的即爲你電腦安裝的版本。
    示例:
    在這裏插入圖片描述
    可見我的是 4.0。
    如果想要查看更細節的版本,操作過程如下:
    在這裏插入圖片描述
  2. 電腦聯網並能夠無障礙訪問 GitHub並下載相關文件。

下載 winsw

WinSW下載地址:https://github.com/winsw/winsw/releases
根據我電腦 .NET 版本下載相關文件:

  • WinSW.NET4.exe
  • sample-allOptions.xml(或者 sample-minimal.xml)

編寫配置文件

我們需要編寫一個和程序(WinSW.NET4.exe)同名的XML文件(WinSW.NET4.xml)作爲winsw的配置文件。
下面簡要的設置一個可以滿足日常需求的帶配置文件的程序的配置。
如:

  • 程序位於:D:\program\my.exe
  • 可執行程序對應的配置文件爲:D:\program\my.conf
    原始方法我在命令行工具中執行程序的方法爲:D:\program\my.exe -c D:\program\my.conf
    接下來就是程序示例:
<service>
  
  <!-- ID of the service. It should be unique across the Windows system-->
  <id>myServiceId</id>
  <!-- Display name of the service -->
  <name>My Service (powered by WinSW)</name>
  <!-- Service description -->
  <description>This service is a service created from a minimal configuration, for  remote control. </description>
  
  <!-- Path to the executable, which should be started -->
  <executable>D:\program\my.exe</executable>
  <arguments>-c D:\program\my.conf</arguments>
  <!--
    OPTION: onfailure
    Defines a sequence of actions, which should be performed if the managed executable fails.
    Supported actions: restart, reboot, none
  -->  
  <onfailure action="restart" delay="60 sec"/>
  <onfailure action="restart" delay="120 sec"/>


  <!--
    OPTION: log
    Defines logging mode for logs produced by the executable.
    Supported modes:
      * append - Rust update the existing log
      * none - Do not save executable logs to the disk
      * reset - Wipe the log files on startup
      * roll - Rotate logs based on size
      * roll-by-time - Rotate logs based on time
      * rotate - Rotate logs based on size, (8 logs, 10MB each). This mode is deprecated, use "roll"
    Default mode: append
    
    Each mode has different settings. 
    See https://github.com/kohsuke/winsw/blob/master/doc/loggingAndErrorReporting.md for more details
  -->
  <log mode="reset">
    <!--
    <setting1/>
    <setting2/>
    -->
  </log>
    <!--
      OPTION: startmode
      Defines start mode of the service.
      Supported modes: Automatic, Manual, Boot, System (latter ones are supported for driver services only)
      Default mode: Automatic
    -->
    <startmode>Automatic</startmode>

</service>

註冊服務

編寫好配置文件之後,記得把配置文件和可執行文件放在一起,這樣winsw才能正確識別配置文件。然後我們打開一個管理員權限的命令提示符或Powershell窗口,然後輸入WinSW.NET4.exe install
在這裏插入圖片描述
對應的服務爲:
在這裏插入圖片描述

卸載服務

同理,WinSW.NET4.exe uninstall
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章