.Net Core 后台托管服务

这里的托管服务不用前端请求,可以随服务启动,可以做定时任务

可以编写一个类,继承于:BackgroundService

using System.Text;

public class ExplortStatisticBgService : BackgroundService
{
    private readonly TestDbContext ctx;
    private readonly ILogger<ExplortStatisticBgService> logger;
    private readonly IServiceScope serviceScope;
    public ExplortStatisticBgService(IServiceScopeFactory scopeFactory)
    {
        this.serviceScope = scopeFactory.CreateScope();
        var sp = serviceScope.ServiceProvider;
        this.ctx = sp.GetRequiredService<TestDbContext>();
        this.logger = sp.GetRequiredService<ILogger<ExplortStatisticBgService>>();
    }
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await DoExecuteAsync();
                await Task.Delay(5000);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取用户统计数据失败");
                await Task.Delay(1000);
            }
        }
    }
    private async Task DoExecuteAsync()
    {
        var items = ctx.Users.GroupBy(u => u.CreationTime.Date)
                        .Select(e => new { Date = e.Key, Count = e.Count() });
        StringBuilder sb = new StringBuilder();
        sb.AppendLine($"Date:{DateTime.Now}");
        foreach (var item in items)
        {
            sb.Append(item.Date).AppendLine($":{item.Count}");
        }
        await File.WriteAllTextAsync("d:/1.txt", sb.ToString());
        logger.LogInformation($"导出完成");
    }
    public override void Dispose()
    {
        base.Dispose();
        serviceScope.Dispose();
    }
}

 

在program.cs 中注册添加:

IServiceCollection services = builder.Services;
services.AddHostedService<ExplortStatisticBgService>();

 第八章/常驻后台的数据导出服务 · 物华天宝/NETBookMaterials - 码云 - 开源中国 (gitee.com)

Part5-9:托管服务的使用_哔哩哔哩_bilibili

posted @ 2022-08-12 22:39  百年俊少  阅读(60)  评论(0编辑  收藏  举报