Skip to content

Instantly share code, notes, and snippets.

@GrillPhil
Last active May 17, 2023 09:50
Show Gist options
  • Save GrillPhil/eb1c4118fc4878a84d7d26b6582bf25c to your computer and use it in GitHub Desktop.
Save GrillPhil/eb1c4118fc4878a84d7d26b6582bf25c to your computer and use it in GitHub Desktop.
class PeriodicHostedService : BackgroundService
{
private readonly TimeSpan _period = TimeSpan.FromSeconds(5);
private readonly ILogger<PeriodicHostedService> _logger;
private readonly IServiceScopeFactory _factory;
private int _executionCount = 0;
public bool IsEnabled { get; set; }
public PeriodicHostedService(
ILogger<PeriodicHostedService> logger,
IServiceScopeFactory factory)
{
_logger = logger;
_factory = factory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using PeriodicTimer timer = new PeriodicTimer(_period);
while (
!stoppingToken.IsCancellationRequested &&
await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
if (IsEnabled)
{
await using AsyncServiceScope asyncScope = _factory.CreateAsyncScope();
SampleService sampleService = asyncScope.ServiceProvider.GetRequiredService<SampleService>();
await sampleService.DoSomethingAsync();
_executionCount++;
_logger.LogInformation(
$"Executed PeriodicHostedService - Count: {_executionCount}");
}
else
{
_logger.LogInformation(
"Skipped PeriodicHostedService");
}
}
catch (Exception ex)
{
_logger.LogInformation(
$"Failed to execute PeriodicHostedService with exception message {ex.Message}. Good luck next round!");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment