Worker.cs 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. namespace BankOperationsUpdate.WorkerService;
  2. public class Worker : BackgroundService
  3. {
  4. private readonly ILogger<Worker> _logger;
  5. private TimeSpan refreshInterval;
  6. private readonly UpdateOperations _updateOperations;
  7. public Worker(ILogger<Worker> logger, UpdateOperations updateOperations, IConfiguration config)
  8. {
  9. _logger = logger;
  10. _updateOperations = updateOperations;
  11. refreshInterval = Int32.TryParse(config.GetSection("RefreshInterval").Value, out int minutes) ? TimeSpan.FromMinutes(5) : TimeSpan.FromMinutes(minutes);
  12. }
  13. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  14. {
  15. _updateOperations.WhenStart();
  16. while (!stoppingToken.IsCancellationRequested) {
  17. try {
  18. _updateOperations.Execute();
  19. }
  20. catch (Exception ex) {
  21. _logger.LogError("Message: {message} \n Source : {source} \n StackTrace: {stackTrace}", ex.Message, ex.Source, ex.StackTrace);
  22. }
  23. _logger.LogInformation("end of period");
  24. await Task.Delay(refreshInterval, stoppingToken);
  25. }
  26. }
  27. }