Skip to content

Instantly share code, notes, and snippets.

@JuergenGutsch
Created November 23, 2022 21:12
Show Gist options
  • Save JuergenGutsch/8244be810a077b2b877d9eb209411589 to your computer and use it in GitHub Desktop.
Save JuergenGutsch/8244be810a077b2b877d9eb209411589 to your computer and use it in GitHub Desktop.
namespace HostedServiceSample;
public class SampleBackgroundService : BackgroundService
{
private readonly ILogger<SampleHostedService> logger;
public SampleBackgroundService(ILogger<SampleHostedService> logger)
{
this.logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
logger.LogInformation("Background service starting");
await Task.Factory.StartNew(async () =>
{
while (!cancellationToken.IsCancellationRequested)
{
logger.LogInformation("Background service executing - {0}", DateTime.Now);
try
{
await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken);
}
catch (OperationCanceledException) { }
}
}, cancellationToken);
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
logger.LogInformation("Background service stopping");
await Task.CompletedTask;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment