diff --git a/Mango.Nop.Services/IMgBackgroundService.cs b/Mango.Nop.Services/IMgBackgroundService.cs new file mode 100644 index 0000000..856a082 --- /dev/null +++ b/Mango.Nop.Services/IMgBackgroundService.cs @@ -0,0 +1,7 @@ +using Microsoft.Extensions.Hosting; + +namespace Mango.Nop.Services; + +public interface IMgBackgroundService : IHostedService, IDisposable +{ +} \ No newline at end of file diff --git a/Mango.Nop.Services/MgBackgroundServiceBase.cs b/Mango.Nop.Services/MgBackgroundServiceBase.cs index d6d629a..1c9b411 100644 --- a/Mango.Nop.Services/MgBackgroundServiceBase.cs +++ b/Mango.Nop.Services/MgBackgroundServiceBase.cs @@ -3,9 +3,20 @@ using Nop.Services.Logging; namespace Mango.Nop.Services; -public abstract class MgBackgroundServiceBase(ILogger logger, IServiceProvider service) : BackgroundService +public abstract class MgBackgroundServiceBase : BackgroundService, IMgBackgroundService { - protected abstract Task OnExecuteAsync(); + 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) { @@ -13,25 +24,33 @@ public abstract class MgBackgroundServiceBase(ILogger logger, IServiceProvider s { try { - await logger.InformationAsync($"MgBackgroundServiceBase.ExecuteAsync(); Processing ExecuteAsync"); - await OnExecuteAsync(); + 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); + 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"); + 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 Logger.InformationAsync("MgBackgroundServiceBase.StopAsync(); Stopping MgBackgroundServiceBase"); await base.StopAsync(cancellationToken); } + + public virtual void Pause(bool pause) => _isPaused = pause; } \ No newline at end of file