.NET6创建Windows服务

.NET6打包部署到Windows Service

1.安装Nuget包

安装以下nuget包支持windows service

安装Microsoft.Extensions.Hosting.WindowsServices

<PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="6.0.10" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.1" />

2.设置ContentRootPath

var options = new WebApplicationOptions
{
    Args = args,
    ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default
};
 
var builder = WebApplication.CreateBuilder(options);

3.启用WIndowsService

通过以下方法即可启用WIndowsService支持

builder.Host.UseWindowsService();

4.发布项目 

发布到文件夹

5.简单安装

通过以下BASH命令,实现安装/开始/停止/删除windows service

安装

set "CDir=%~dp0"

sc.exe create "MyService" start=auto binpath="%CDir%MyService.exe --environment Development"
pause
 
启动:sc.exe start "MyService"
停止:sc.exe stop "MyService"
删除:sc.exe delete "MyService"
 
全部脚本
 1.
@echo off
% bat脚本获取管理员权限 %
%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit

% 1.安装服务 %
set "CDir=%~dp0"
sc.exe create "MyService" start=auto binpath="%CDir%MyService.exe --environment Development"

% 2.启动服务 %
sc.exe start "MyService"
% 3.停止服务 %    
sc.exe stop "MyService"
% 4.删除服务 %
sc.exe delete "MyService"

pause
安装服务

 2.

----------------------安装----------------------
set serviceName=TestTask
set serviceFilePath="F:\WebApplication.exe"
set serviceDescription="测试任务"

sc create %serviceName%  BinPath=%serviceFilePath%
sc config %serviceName%    start=auto  
sc config %serviceName%    start=delayed-auto   
sc description %serviceName%  %serviceDescription%
sc failure %serviceName%  reset= 0 actions= restart/1200000
sc start  %serviceName%
pause

----------------------卸载----------------------
set serviceName=TestTask
sc stop   %serviceName% 
sc delete %serviceName% 
pause
View Code

 

6.安装打包工具

 。。。。。。。。。。。。。。。。。。

 

 

服务命名,Program.cs文件代码:

 

 
    public class Program
    {
        public static void Main(string[] args)
        {
            IHost host = Host.CreateDefaultBuilder(args)
                 .UseWindowsService(options =>
                 {
                     //给服务命名,在Windows服务中的会显示名字
                     options.ServiceName = "NET6故里2130";
                 })
                .ConfigureServices(services =>
                {
                    services.AddHostedService<Worker>();
                })
                .Build();
 
            host.Run();
        }
View Code

 

服务里面写启动,停止,以及执行任务,Worker.cs中写

里面的业务就是,检测启动,停止,每次执行任务都输出

namespace WorkerServiceDemo
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;
        private readonly string filePath = "D:\\Service1.txt";
 
        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }
 
        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                using (FileStream stream = new FileStream(filePath, FileMode.Append))
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.WriteLine($"{DateTimeOffset.Now},服务执行!");
                }
                await Task.Delay(1000, stoppingToken);
            }
        }
        /// <summary>
        /// 服务启动
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override Task StartAsync(CancellationToken cancellationToken)
        {
 
            using (FileStream stream = new FileStream(filePath, FileMode.Append))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine($"{DateTime.Now},服务启动!");
            }
 
            return base.StartAsync(cancellationToken);
        }
        /// <summary>
        /// 服务停止
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            using (FileStream stream = new FileStream(filePath, FileMode.Append))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine($"{DateTime.Now},服务停止!");
            }
 
            return base.StopAsync(cancellationToken);
        }
    }
}
View Code

 

转:https://blog.csdn.net/u012563853/article/details/131198053

 https://www.cnblogs.com/RainFate/p/16784858.html

 
posted @ 2023-08-07 15:16  bxzjzg  阅读(374)  评论(0编辑  收藏  举报