Last active
November 23, 2022 21:06
-
-
Save JuergenGutsch/847789b0970b2b6cbdbaa439f5090308 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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