Created
November 23, 2022 21:12
-
-
Save JuergenGutsch/8244be810a077b2b877d9eb209411589 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
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