using Fake.UnitOfWork; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Oms.Application.Shared; namespace Oms.Application.Workers; /// /// 营销定时任务:释放过期券锁、结算 Pending 分成。 /// public class MarketingBackgroundWorker : BackgroundService { private static readonly TimeSpan PollInterval = TimeSpan.FromMinutes(1); private const int BatchSize = 50; private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; public MarketingBackgroundWorker( IServiceScopeFactory scopeFactory, ILogger logger) { _scopeFactory = scopeFactory; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { await ProcessAsync(stoppingToken); } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogError(ex, "营销后台任务异常"); } try { await Task.Delay(PollInterval, stoppingToken); } catch (OperationCanceledException) { break; } } } private async Task ProcessAsync(CancellationToken cancellationToken) { using var scope = _scopeFactory.CreateScope(); var unitOfWorkManager = scope.ServiceProvider.GetRequiredService(); using var unitOfWork = unitOfWorkManager.Begin(); var couponManager = scope.ServiceProvider.GetRequiredService(); await couponManager.ReleaseExpiredLocksAsync(BatchSize, cancellationToken); var commissionManager = scope.ServiceProvider.GetRequiredService(); await commissionManager.SettlePendingAsync(BatchSize, cancellationToken); await unitOfWork.CompleteAsync(cancellationToken); } }