Skip to content

Instantly share code, notes, and snippets.

@alistairjevans
Created April 6, 2020 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alistairjevans/e200732d75283e4bd2aa7a19b41ddab6 to your computer and use it in GitHub Desktop.
Save alistairjevans/e200732d75283e4bd2aa7a19b41ddab6 to your computer and use it in GitHub Desktop.
// Riffing on https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio
public class TimedHostedService : IHostedService, IDisposable
{
private readonly ILogger<TimedHostedService> _logger;
private readonly IServiceProvider _provider;
private Timer _timer;
public TimedHostedService(IServiceProvider provider, ILogger<TimedHostedService> logger)
{
_provider = provider;
_logger = logger;
}
public Task StartAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service running.");
_timer = new Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
private void DoWork(object state)
{
using (var serviceScope = provider.CreateScope())
{
var provider = serviceScope.ServiceProvider;
var service = provider.GetRequiredService<MyService>();
// Do stuff...
// Scope is disposed here.
}
}
public Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment