背景介紹:
項目環境為ASP.NET Core 2.1.2。
需要在項目啟動時運行一個定時任務,在后台每隔一定時間執行任務。
實現方法:
1、寫一個任務服務類繼承BackgroundService
1 public class APIDataService : BackgroundService 2 { 3 protected override async Task ExecuteAsync(CancellationToken stoppingToken) 4 { 5 while (!stoppingToken.IsCancellationRequested) 6 { 7 try 8 { 9 //需要執行的任務 10 11 } 12 catch (Exception ex) 13 { 14 LogHelper.Error(ex.Message); 15 } 16 await Task.Delay(1000, stoppingToken);//等待1秒 17 } 18 } 19 }
2、在Startup.cs中注入
1 public void ConfigureServices(IServiceCollection services) 2 { 3 ... 4 services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, APIDataService>(); 5 }
3、運行代碼,進行測試