diff --git a/Mango.Nop.Services/MgBackgroundServiceBase.cs b/Mango.Nop.Services/MgBackgroundServiceBase.cs new file mode 100644 index 0000000..d6d629a --- /dev/null +++ b/Mango.Nop.Services/MgBackgroundServiceBase.cs @@ -0,0 +1,37 @@ +using Microsoft.Extensions.Hosting; +using Nop.Services.Logging; + +namespace Mango.Nop.Services; + +public abstract class MgBackgroundServiceBase(ILogger logger, IServiceProvider service) : BackgroundService +{ + protected abstract Task OnExecuteAsync(); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try + { + await logger.InformationAsync($"MgBackgroundServiceBase.ExecuteAsync(); Processing ExecuteAsync"); + await OnExecuteAsync(); + } + catch (Exception ex) + { + await logger.ErrorAsync($"MgBackgroundServiceBase.ExecuteAsync(); Failure while processing ExecuteAsync", ex, null); + } + } + } + + public override async Task StartAsync(CancellationToken cancellationToken) + { + 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); + } +} \ No newline at end of file