Created
April 6, 2020 11:55
-
-
Save alistairjevans/e200732d75283e4bd2aa7a19b41ddab6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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