.NET CORE 3.0新增了Worker Services的新項目模板,能夠編寫長時間運行的後臺服務,而且能輕鬆的部署成windows服務或linux守護程序。若是安裝的vs2019是中文版本,Worker Services變成了輔助角色服務。Worker Services 咱也不知道怎麼翻譯成了這個名稱,咱也不敢亂翻譯,下文就保持原名稱。。。,本文將會演示如何建立一個Worker Services項目,而且部署爲windows服務或linux守護程序運行;linux
項目建立成功以後,您會看到建立了兩個類:Program和Worker。windows
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>(); });
Program類跟ASP.NET Core Web應用程序很是相似,不一樣之處沒有了startup類,而且把worker服務添加到DI container中。
async
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) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } } }
worker只是一個簡單的類,它繼承自BackgroundService ,然後者又實現IHostedService接口。ide
默認的worker演示,沒隔1秒,循環打印運行的時間。
工具
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseWindowsService() .ConfigureServices((hostContext, services) => { services.AddHostedService<Worker>(); });
dotnet publish -c Release -o C:\WorkerPub
sc.exe create DemoWorkService binPath=C:\WorkerPub\WorkerService1.exe
查看服務狀態使用一下命令ui
sc.exe query DemoWorkService
啓動命令spa
sc.exe start DemoWorkService
在服務列表查看,DemoWorkService已安裝成功 翻譯
停用 、刪除命令code
sc.exe stop DemoWorkService
sc.exe delete DemoWorkService
部署linux守護程序也是很方便的執行一下兩個步驟便可:orm
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseSystemd() .ConfigureServices((hostContext, services) => { services.AddHostedService<Worker>(); });