using Microsoft.Extensions.Hosting; using Nop.Services.Logging; namespace Mango.Nop.Services; public abstract class MgBackgroundServiceBase : BackgroundService, IMgBackgroundService { private bool _isPaused; protected int ExecuteIntervalMs; protected readonly ILogger Logger; protected MgBackgroundServiceBase(ILogger logger, IServiceProvider service, int executeIntervalMs) { Logger = logger; ExecuteIntervalMs = executeIntervalMs; } protected abstract Task OnExecuteAsync(CancellationToken stoppingToken); protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { await Task.Delay(ExecuteIntervalMs, stoppingToken); if (_isPaused || stoppingToken.IsCancellationRequested) continue; await Logger.InformationAsync($"MgBackgroundServiceBase.ExecuteAsync(); Processing ExecuteAsync"); await OnExecuteAsync(stoppingToken); } catch (Exception ex) { await Logger.ErrorAsync($"MgBackgroundServiceBase.ExecuteAsync(); Failure while processing ExecuteAsync", ex, null); } } } public override async Task StartAsync(CancellationToken cancellationToken) { Pause(false); await Logger.InformationAsync("MgBackgroundServiceBase.ExecuteAsync(); Starting MgBackgroundServiceBase"); await base.StartAsync(cancellationToken); } public override async Task StopAsync(CancellationToken cancellationToken) { await Logger.InformationAsync("MgBackgroundServiceBase.StopAsync(); Stopping MgBackgroundServiceBase"); await base.StopAsync(cancellationToken); } public virtual void Pause(bool pause) => _isPaused = pause; }