title: How can I create a BackGround service that runs a function every given period of time ? Using C# (asp.net core 3.1.1)
body: <p>I'm trying to make call to a function every specified interval of time, for that m using Background service, here is what I have done:
  Here is the Alerting controller where I have the function:</p>
  
  <pre><code>public class AlertingController : ControllerBase
  {
      private readonly DatabaseContext _context;
      private readonly IMapper _mapper;
  
      public AlertingController(DatabaseContext context, IMapper mapper)
      {
          _context = context ?? throw new ArgumentNullException(nameof(context));
          _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
      }
      public AlertingController()
      {
  
      }
  //function that adds in the DB
      public async Task&lt;AlertingResponse&gt; GetAlertingToDB()
      {
          AlertingResponse dataGet;
  
          using (var httpClient = new HttpClient())
          {
              using (var response = await httpClient
                  .GetAsync(MetricApiLink))
              {
                  string apiResponse = await response.Content.ReadAsStringAsync();
                  dataGet = JsonConvert.DeserializeObject&lt;AlertingResponse&gt;(apiResponse);
              }
          }
          if (dataGet.data.alerts != null || dataGet.data.alerts.Count &gt; 0)
          {
              foreach (var alert in dataGet.data.alerts)
              {
                  CreateAlertQuery QueryAlert = new CreateAlertQuery();
                  QueryAlert.Name = alert.labels.alertname;
                  QueryAlert.Instance = alert.labels.instance;
                  QueryAlert.Serverity = alert.labels.severity;
                  QueryAlert.Summary = alert.annotations.summary;
                  QueryAlert.State = alert.state;
                  QueryAlert.ActiveAt = alert.activeAt;
                  var _Alert = _mapper.Map&lt;AlertingDataModel&gt;(QueryAlert);
                  _context.Alertings.Add(_Alert);
                  await _context.SaveChangesAsync();
              }
          }
  
          return null;
      }
  }
  </code></pre>
  
  <p>I have tested the method with a HTTPGET request, it works fine, add the alerts into my database:</p>
  
  <p><a href="https://i.stack.imgur.com/bRBL6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bRBL6.png" alt="enter image description here"></a></p>
  
  <p>I have created a scooped service where I called the function <code>GetAlertingToDB()</code>:</p>
  
  <pre><code>    internal interface IScopedAlertingService
      {
          Task DoWork(CancellationToken stoppingToken);
      }
      public class ScopedAlertingService : IScopedAlertingService
      {
          private int executionCount = 0;
          private readonly ILogger _logger;
  
      public ScopedAlertingService(ILogger&lt;ScopedAlertingService&gt; logger)
      {
          _logger = logger;
      }
  
      public async Task DoWork(CancellationToken stoppingToken)
      {
          AlertingController _AlertingToDB = new AlertingController();
          while (!stoppingToken.IsCancellationRequested)
          {
              executionCount++;
  
              _logger.LogInformation(
                  "Scoped Processing Service is working. Count: {Count}", executionCount);
  
              await _AlertingToDB.GetAlertingToDB();
  
              await Task.Delay(10000, stoppingToken);
          }
      }
  }
  </code></pre>
  
  <p>I have also created the Class that will consume my service, and will run in the BackGround:</p>
  
  <pre><code>public class ConsumeScopedServiceHostedService : BackgroundService
  {
      private readonly ILogger&lt;ConsumeScopedServiceHostedService&gt; _logger;
  
      public ConsumeScopedServiceHostedService(IServiceProvider services,
          ILogger&lt;ConsumeScopedServiceHostedService&gt; logger)
      {
          Services = services;
          _logger = logger;
      }
  
      public IServiceProvider Services { get; }
  
      protected override async Task ExecuteAsync(CancellationToken stoppingToken)
      {
          _logger.LogInformation(
              "Consume Scoped Service Hosted Service running.");
  
          await DoWork(stoppingToken);
      }
  
      private async Task DoWork(CancellationToken stoppingToken)
      {
          _logger.LogInformation(
              "Consume Scoped Service Hosted Service is working.");
  
          using (var scope = Services.CreateScope())
          {
              var scopedProcessingService =
                  scope.ServiceProvider
                      .GetRequiredService&lt;IScopedAlertingService&gt;();
  
              await scopedProcessingService.DoWork(stoppingToken);
          }
      }
  
      public override async Task StopAsync(CancellationToken stoppingToken)
      {
          _logger.LogInformation(
              "Consume Scoped Service Hosted Service is stopping.");
  
          await Task.CompletedTask;
      }
  }
  </code></pre>
  
  <p>I injected the dependencies on the Startup Class and added the hosted service:</p>
  
  <pre><code>        services.AddHostedService&lt;ConsumeScopedServiceHostedService&gt;();
          services.AddScoped&lt;IScopedAlertingService, ScopedAlertingService&gt;();
  </code></pre>
  
  <p>The functions are working just fine untill a call the <code>GetAlertingToDB()</code> function and it doesn't work.</p>
  
  <p>Any help would be great, thanks everyone :)</p>