protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { while (!stoppingToken.IsCancellationRequested) { var keys = (await _keyRepository.FindCreatedBefore( DateTime.Now.Subtract(TimeSpan.FromMinutes(_config.TimeToLiveInMinutes)), _config.BatchSize)) .ToList(); foreach (var key in keys) { try { var elapsed = await Measurements.Timer.MeasureAsync(async() => await _archiver.Save(new Key { Body = key.Body, Id = key.ShortSha })); WorkerMeasurements.MeasureTime(_metrics, elapsed); WorkerMeasurements.MeasureArchiveOccurrence(_metrics); await _keyRepository.Remove(key.Id); } catch (Exception e) { WorkerMeasurements.MeasureErrorOccurrence(_metrics); _logger.LogError(e, "exception caught"); } if (stoppingToken.IsCancellationRequested) { return; } } _logger.LogDebug($"Archived {keys.Count} keys at {DateTime.Now}"); if (stoppingToken.IsCancellationRequested) { return; } await Task.Delay(TimeSpan.FromSeconds(_config.BatchIntervalInSeconds), stoppingToken); } } catch (NpgsqlException) { _logger.LogWarning("db connection issues"); } catch (OperationCanceledException) { // do nothing } }