托管服务
//案例:数据的定时导出 1 public class ExplortStatisticBgService : BackgroundService 2 { 3 private readonly TestDbContext ctx; 4 private readonly ILogger<ExplortStatisticBgService> logger; 5 private readonly IServiceScope serviceScope; 6 public ExplortStatisticBgService(IServiceScopeFactory scopeFactory) 7 { 8 this.serviceScope = scopeFactory.CreateScope(); 9 var sp = serviceScope.ServiceProvider; 10 this.ctx = sp.GetRequiredService<TestDbContext>(); 11 this.logger = sp.GetRequiredService<ILogger<ExplortStatisticBgService>>(); 12 } 13 protected override async Task ExecuteAsync(CancellationToken stoppingToken) 14 { 15 while (!stoppingToken.IsCancellationRequested) 16 { 17 try 18 { 19 await DoExecuteAsync(); 20 await Task.Delay(5000); 21 } 22 catch (Exception ex) 23 { 24 logger.LogError(ex, "获取用户统计数据失败"); 25 await Task.Delay(1000); 26 } 27 } 28 } 29 private async Task DoExecuteAsync() 30 { 31 var items = ctx.Users.GroupBy(u => u.CreationTime.Date) 32 .Select(e => new { Date = e.Key, Count = e.Count() }); 33 StringBuilder sb = new StringBuilder(); 34 sb.AppendLine($"Date:{DateTime.Now}"); 35 foreach (var item in items) 36 { 37 sb.Append(item.Date).AppendLine($":{item.Count}"); 38 } 39 await File.WriteAllTextAsync("d:/1.txt", sb.ToString()); 40 logger.LogInformation($"导出完成"); 41 } 42 public override void Dispose() 43 { 44 base.Dispose(); 45 serviceScope.Dispose(); 46 } 47 }
静,静,静