Skip to content

Instantly share code, notes, and snippets.

@JuergenGutsch
Last active November 23, 2022 21:06
Show Gist options
  • Save JuergenGutsch/847789b0970b2b6cbdbaa439f5090308 to your computer and use it in GitHub Desktop.
Save JuergenGutsch/847789b0970b2b6cbdbaa439f5090308 to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace HostedServiceSample
{
public class SampleHostedService : IHostedService
{
private readonly ILogger<SampleHostedService> logger;
public SampleHostedService(ILogger<SampleHostedService> logger)
{
this.logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
logger.LogInformation("Hosted service starting");
return Task.Factory.StartNew(async () =>
{
while (!cancellationToken.IsCancellationRequested)
{
logger.LogInformation("Hosted service executing - {0}", DateTime.Now);
try
{
await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken);
}
catch (OperationCanceledException) { }
}
}, cancellationToken);
}
public Task StopAsync(CancellationToken cancellationToken)
{
logger.LogInformation("Hosted service stopping");
return Task.CompletedTask;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment