Last active
November 1, 2018 20:40
-
-
Save Saladressing/fd25ba199777bb9f497e98ec03bc88b0 to your computer and use it in GitHub Desktop.
BackgroundService Example in NET core
This file contains hidden or 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
// 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