using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics;
static async Task Main(string[] args)
Log.Logger = new LoggerConfiguration().CreateLogger();
await new HostBuilder().ConfigureServices(services =>
services.AddHostedService<SampleHostedService>();
}).ConfigureLogging(logging => logging.AddConsole())
public class SampleHostedService : BackgroundService
readonly ILogger<SampleHostedService> _logger;
readonly IHostApplicationLifetime _hostApplicationLifetime;
public SampleHostedService(ILogger<SampleHostedService> logger, IHostApplicationLifetime hostApplicationLifetime)
_hostApplicationLifetime = hostApplicationLifetime;
public override async Task StartAsync(CancellationToken cancellationToken)
_logger.LogInformation("SampleHostedService started at: {time}", DateTimeOffset.Now);
new Timer((o) => _hostApplicationLifetime.StopApplication(), null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
await base.StartAsync(cancellationToken);
public override async Task StopAsync(CancellationToken cancellationToken)
var stopWatch = Stopwatch.StartNew();
_logger.LogInformation("SampleHostedService stopped at: {time}", DateTimeOffset.Now);
await base.StopAsync(cancellationToken);
_logger.LogInformation("SampleHostedService took {ms} ms to stop.", stopWatch.ElapsedMilliseconds);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
while (!stoppingToken.IsCancellationRequested)
_logger.LogInformation("SampleHostedService running at: {time}", DateTimeOffset.Now);
await Task.Delay(TimeSpan.FromSeconds(120));