using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ZR.Service.mes.andon { public class ScheduledBackgroundService:BackgroundService { private readonly ILogger _logger; private readonly IServiceScopeFactory _scopeFactory; private readonly TimeSpan _interval = TimeSpan.FromMinutes(5); public ScheduledBackgroundService( ILogger logger, IServiceScopeFactory scopeFactory) { _logger = logger; _scopeFactory = scopeFactory; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation($"定时后台服务启动,执行间隔: {_interval.TotalMinutes}分钟"); // 延迟启动,等待应用完全初始化 await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken); while (!stoppingToken.IsCancellationRequested) { try { _logger.LogInformation($"开始执行定时任务: {DateTime.Now:HH:mm:ss}"); //// 使用 Scope 获取 Scoped 服务 //using (var scope = _scopeFactory.CreateScope()) //{ // var myService = scope.ServiceProvider.GetRequiredService(); // await myService.ProcessDataAsync(); //} _logger.LogInformation($"定时任务完成"); } catch (Exception ex) { _logger.LogError(ex, "定时任务执行异常"); } // 等待指定间隔 await Task.Delay(_interval, stoppingToken); } _logger.LogInformation("定时后台服务停止"); } } }