Fix cleanup service
Fixes the issue where the job would run only once, instead of peridiocally.
This commit is contained in:
parent
442ac6c6e9
commit
6ff2d69cb2
|
|
@ -12,40 +12,27 @@ namespace Elsa.Retention.HostedServices
|
|||
/// <summary>
|
||||
/// Periodically wipes workflow instances and their execution logs.
|
||||
/// </summary>
|
||||
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<CleanupOptions> 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<CleanupJob>();
|
||||
await job.ExecuteAsync();
|
||||
|
||||
_timer.Change(_options.SweepInterval.ToTimeSpan(), Timeout.InfiniteTimeSpan);
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(_interval, stoppingToken);
|
||||
await job.ExecuteAsync(stoppingToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue