Skip to content

Instantly share code, notes, and snippets.

@Saladressing
Last active November 1, 2018 20:40
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 Saladressing/fd25ba199777bb9f497e98ec03bc88b0 to your computer and use it in GitHub Desktop.
Save Saladressing/fd25ba199777bb9f497e98ec03bc88b0 to your computer and use it in GitHub Desktop.
BackgroundService Example in NET core
// TestBackgroundService.cs
public class TestBackgroundService : BackgroundService, IHostedService
{
private readonly ILogger _logger;
public TestBackgroundService(ILogger<TestBackgroundService> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
cancellationToken.Register(() => _logger.LogInformation("Service is stopping."));
while (!cancellationToken.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromMinutes(10), cancellationToken);
_logger.LogInformation("Attempting to do actions.");
}
}
}
// Inside Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, TestBackgroundService>();
...
}
// Inside Program.cs (Apply a timeout to allow the services to shutdown successfully)
...
CreateDefaultBuilder(args)
...
.UseShutdownTimeout(TimeSpan.FromSeconds(10))
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment