title: Run async hosted service every 5 minutes in ASP.NET Core
body: <p>The ASP.NET Core <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services" rel="nofollow noreferrer">docs</a> for background services show a number of implementation examples.</p>
  <p>There's an example for starting a service on a <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-6.0&amp;tabs=visual-studio#timed-background-tasks" rel="nofollow noreferrer">timer</a>, though it's synchronous. There's another example which is asynchronous, for starting a service with a <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-6.0&amp;tabs=visual-studio#consuming-a-scoped-service-in-a-background-task" rel="nofollow noreferrer">scoped dependency</a>.</p>
  <p>I need to do both: start a service every 5 minutes, and it has scoped dependencies. There's no example for that.</p>
  <p>I combined both examples, but I'm unsure of a safe way to use <code>Timer</code> with an async <code>TimerCallback</code>.</p>
  <p>e.g.</p>
  <pre class="lang-cs prettyprint-override"><code>public class MyScheduler : IHostedService
  {
    private Timer? _timer;
    private readonly IServiceScopeFactory _serviceScopeFactory;
  
    public MyScheduler(IServiceScopeFactory serviceScopeFactory) =&gt; _serviceScopeFactory = serviceScopeFactory;
  
    public void Dispose() =&gt; _timer?.Dispose();
  
    public Task StartAsync(CancellationToken cancellationToken)
    {
      _timer = new Timer((object? state) =&gt; {
        using var scope = _serviceScopeFactory.CreateScope();
        var myService = scope.ServiceProvider.GetRequiredService&lt;IMyService&gt;();
        await myService.Execute(cancellationToken);            // &lt;------ problem
      }), null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
  
      return Task.CompletedTask;
    }
  
    public Task StopAsync(CancellationToken cancellationToken) {
      _timer?.Change(Timeout.Infinite, 0);
      return Task.CompletedTask;
    }
  
  }
  </code></pre>
  <p>The timer takes a sync callback, so the problem is the <code>await</code>. What's a safe way to call an async service?</p>