(精华2020年6月17日更新)asp.net core3.1实战专题 Worker Service构建系统服务实现任务调度

使用vs2019创建Worker Service程序

首先nuget安装

Microsoft.Extensions.Hosting.Windows

在Program中添加UseWindowsService()

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                }).UseWindowsService();//部署windows值守服务
    }

实际任务执行代码Worker类

public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                //实际要执行的任务代码
                await Task.Delay(8640000, stoppingToken);
            }
        }
    }

发布程序后在程序目录用cmd执行以下代码

sc.exe create 服务名称 binpath= xxxx.exe

你可能感兴趣的:(.NET,Core3.1实战专题,c#,asp.net)