netcore2.1 在後臺執行一個任務
在 ASP.NET Core 2.1中, 提供了一個名為BackgroundService的類,在 Microsoft.Extensions.Hosting名稱空間中,其程式碼為
1 namespace Microsoft.Extensions.Hosting 2 { 3// 4// 摘要: 5//Base class for implementing a long running Microsoft.Extensions.Hosting.IHostedService. 6public abstract class BackgroundService : IHostedService, IDisposable 7{ 8protected BackgroundService(); 9 10public virtual void Dispose(); 11// 12// 摘要: 13//Triggered when the application host is ready to start the service. 14// 15// 引數: 16//cancellationToken: 17//Indicates that the start process has been aborted. 18public virtual Task StartAsync(CancellationToken cancellationToken); 19// 20// 摘要: 21//Triggered when the application host is performing a graceful shutdown. 22// 23// 引數: 24//cancellationToken: 25//Indicates that the shutdown process should no longer be graceful. 26[AsyncStateMachine(typeof(<StopAsync>d__4))] 27public virtual Task StopAsync(CancellationToken cancellationToken); 28// 29// 摘要: 30//This method is called when the Microsoft.Extensions.Hosting.IHostedService starts. 31//The implementation should return a task that represents the lifetime of the long 32//running operation(s) being performed. 33// 34// 引數: 35//stoppingToken: 36//Triggered when Microsoft.Extensions.Hosting.IHostedService.StopAsync(System.Threading.CancellationToken) 37//is called. 38// 39// 返回結果: 40//A System.Threading.Tasks.Task that represents the long running operations. 41protected abstract Task ExecuteAsync(CancellationToken stoppingToken); 42} 43 }
可以看出它是繼承自 IHostedService, IDisposable , 而我們只需要繼承並實現它的 ExecuteAsync 即可。
也就是說,我們只需在這個方法內寫下這個服務需要做的事,
1 internal class TokenRefreshService : BackgroundService 2{ 3private readonly ILogger _logger; 4 5public TokenRefreshService(ILogger<TokenRefresh2Service> logger) 6{ 7_logger = logger; 8} 9 10protected override async Task ExecuteAsync(CancellationToken stoppingToken) 11{ 12_logger.LogInformation("Service starting"); 13 14while (!stoppingToken.IsCancellationRequested) 15{ 16_logger.LogInformation(DateTime.Now.ToLongTimeString() + ": Refresh Token!");//在此寫需要執行的任務 17await Task.Delay(5000, stoppingToken); 18} 19 20_logger.LogInformation("Service stopping"); 21} 22}
然後在Startup中註冊服務。
1// This method gets called by the runtime. Use this method to add services to the container. 2public void ConfigureServices(IServiceCollection services) 3{ 4services.Configure<CookiePolicyOptions>(options => 5{ 6// This lambda determines whether user consent for non-essential cookies is needed for a given request. 7options.CheckConsentNeeded = context => true; 8options.MinimumSameSitePolicy = SameSiteMode.None; 9}); 10 11 12services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 13 14 15services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, TokenRefreshService>(); 16 17 18 19}
注意 注意 注意
1. 當IIS上部署的專案啟動後,後臺任務隨之啟動,任務執行相應的log正常輸出。
2. 手動回收對應的應用程式池,任務執行相應的log輸出停止。
3. 重新請求該網站,後臺任務隨之啟動,任務執行相應的log重新開始輸出。
所以不建議在這樣的後臺任務中做一些需要固定定時執行的業務處理類的操作,但對於快取重新整理類的操作還是可以的,因為當應用程式池回收後再次執行的時候,後臺任務會隨著啟動。