title: How to run a single instance of a BackgroundService?
body: <p>I have a <code>BackgroundService</code> that I require to run every 4 hours. I was under the impression it would run only a single instance. Recently I noticed some duplicate data and it turns that my <code>BackgroundService</code> is running multiple instance and each instance seems to be isolated eg can't share state information.</p>
  <p>I have it as a HostedService in the start up file:</p>
  <pre><code>services.AddHostedService&lt;MyBackgroundTask&gt;();
  </code></pre>
  <p>Example of the background service:</p>
  <pre><code>  public class MyBackgroundTask : BackgroundService
  {
  
      protected override async Task ExecuteAsync(CancellationToken stoppingToken)
      {
  
          await Task.Yield();
  
          while (!stoppingToken.IsCancellationRequested)
          {
  
              try
              {
                  // do some calculations
  
                  await Task.Delay(TimeSpan.FromHours(4), stoppingToken);
              }
              catch (Exception e)
              {
  
                  continue;
              }
  
          }
      }
  }
  </code></pre>
  <p>I have tried adding it as a singleton, but it doesn't seem to execute on load, any advise on what I should try?</p>