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.
 6     public abstract class BackgroundService : IHostedService, IDisposable
 7     {
 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重新開始輸出。

所以不建議在這樣的后台任務中做一些需要固定定時執行的業務處理類的操作,但對於緩存刷新類的操作還是可以的,因為當應用程序池回收后再次運行的時候,后台任務會隨着啟動。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM