From 6ff2d69cb24459d1486e73d033039fe5fc1a33b3 Mon Sep 17 00:00:00 2001 From: Sipke Schoorstra Date: Fri, 29 Oct 2021 14:58:43 +0200 Subject: [PATCH] Fix cleanup service Fixes the issue where the job would run only once, instead of peridiocally. --- .../HostedServices/CleanupService.cs | 33 ++++++------------- 1 file changed, 10 insertions(+), 23 deletions(-) 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