netcore2.1 在後臺執行一個任務
阿新 • • 發佈:2018-12-09
在 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. 6 public abstract class BackgroundService : IHostedService, IDisposable7 { 8 protected BackgroundService(); 9 10 public 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.18 public 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))] 27 public 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. 41 protected abstract Task ExecuteAsync(CancellationToken stoppingToken); 42 } 43 }
可以看出它是繼承自 IHostedService, IDisposable , 而我們只需要繼承並實現它的 ExecuteAsync 即可。
也就是說,我們只需在這個方法內寫下這個服務需要做的事,
1 internal class TokenRefreshService : BackgroundService 2 { 3 private readonly ILogger _logger; 4 5 public TokenRefreshService(ILogger<TokenRefresh2Service> logger) 6 { 7 _logger = logger; 8 } 9 10 protected override async Task ExecuteAsync(CancellationToken stoppingToken) 11 { 12 _logger.LogInformation("Service starting"); 13 14 while (!stoppingToken.IsCancellationRequested) 15 { 16 _logger.LogInformation(DateTime.Now.ToLongTimeString() + ": Refresh Token!");//在此寫需要執行的任務 17 await 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. 2 public void ConfigureServices(IServiceCollection services) 3 { 4 services.Configure<CookiePolicyOptions>(options => 5 { 6 // This lambda determines whether user consent for non-essential cookies is needed for a given request. 7 options.CheckConsentNeeded = context => true; 8 options.MinimumSameSitePolicy = SameSiteMode.None; 9 }); 10 11 12 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 13 14 15 services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, TokenRefreshService>(); 16 17 18 19 }
注意 注意 注意
1. 當IIS上部署的專案啟動後,後臺任務隨之啟動,任務執行相應的log正常輸出。
2. 手動回收對應的應用程式池,任務執行相應的log輸出停止。
3. 重新請求該網站,後臺任務隨之啟動,任務執行相應的log重新開始輸出。
所以不建議在這樣的後臺任務中做一些需要固定定時執行的業務處理類的操作,但對於快取重新整理類的操作還是可以的,因為當應用程式池回收後再次執行的時候,後臺任務會隨著啟動。