Created
April 6, 2020 00:07
-
-
Save giridharprakash/c5edefb3dc926cfc6036285baedbd3e8 to your computer and use it in GitHub Desktop.
dotnet core background hosted service with dependency injection and runs every 5 seconds
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
public class EmailBackgroundService : BackgroundService | |
{ | |
private readonly IServiceProvider _serviceProvider; | |
private readonly ILogger<EmailBackgroundService> _logger; | |
public EmailBackgroundService(IServiceProvider serviceProvider, ILogger<EmailBackgroundService> logger) | |
{ | |
_serviceProvider = serviceProvider; | |
_logger = logger; | |
} | |
protected override async Task ExecuteAsync(CancellationToken stoppingToken) | |
{ | |
while (!stoppingToken.IsCancellationRequested) | |
{ | |
await RunSomeprocess(); | |
await Task.Delay(5000, stoppingToken); | |
} | |
} | |
private async Task RunSomeprocess() | |
{ | |
using var providerScope = _serviceProvider.CreateScope(); | |
var userService = providerScope.ServiceProvider.GetService<IUserService>(); | |
_logger.Log( LogLevel.Information , $"{userService.GetUserId()}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment