Created
April 6, 2020 14:15
-
-
Save alistairjevans/be526d93eaf5a40b62d78fb0076e7111 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 workItem = provider.GetRequiredService<IWorkItem>(); | |
workItem.Run(); | |
// 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(); | |
} | |
} | |
internal interface IWorkItem | |
{ | |
void Run(); | |
} | |
// Register this as a transient implementation of IWorkItem. | |
internal class WorkItem : IWorkItem | |
{ | |
private IMyService _service1; | |
private IMyOtherService _service2; | |
public WorkItem(IMyService service, IMyOtherService otherService) | |
{ | |
} | |
public void Run() | |
{ | |
// Do stuff. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment