diff --git a/src/modules/retention/Elsa.Retention/HostedServices/CleanupService.cs b/src/modules/retention/Elsa.Retention/HostedServices/CleanupService.cs index 08482213a..2d60d37b5 100644 --- a/src/modules/retention/Elsa.Retention/HostedServices/CleanupService.cs +++ b/src/modules/retention/Elsa.Retention/HostedServices/CleanupService.cs @@ -12,40 +12,27 @@ namespace Elsa.Retention.HostedServices /// /// Periodically wipes workflow instances and their execution logs. /// - public class CleanupService : IHostedService, IAsyncDisposable + public class CleanupService : BackgroundService { private readonly IServiceScopeFactory _serviceScopeFactory; - private readonly CleanupOptions _options; - private readonly Timer _timer; + private readonly TimeSpan _interval; public CleanupService(IOptions options, IServiceScopeFactory serviceScopeFactory) { _serviceScopeFactory = serviceScopeFactory; - _options = options.Value; - _timer = new Timer(ExecuteAsync, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); + _interval = options.Value.SweepInterval.ToTimeSpan(); } - public Task StartAsync(CancellationToken cancellationToken) - { - _timer.Change(_options.SweepInterval.ToTimeSpan(), Timeout.InfiniteTimeSpan); - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - _timer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); - return Task.CompletedTask; - } - - public async ValueTask DisposeAsync() => await _timer.DisposeAsync(); - - private async void ExecuteAsync(object state) + protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using var scope = _serviceScopeFactory.CreateScope(); var job = scope.ServiceProvider.GetRequiredService(); - await job.ExecuteAsync(); - - _timer.Change(_options.SweepInterval.ToTimeSpan(), Timeout.InfiniteTimeSpan); + + while (!stoppingToken.IsCancellationRequested) + { + await Task.Delay(_interval, stoppingToken); + await job.ExecuteAsync(stoppingToken); + } } } } \ No newline at end of file