Created
January 4, 2021 17:44
-
-
Save vcaraulean/56b6a49bf55485da9651fb6dbd1dfa51 to your computer and use it in GitHub Desktop.
This file contains 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
public class BackgroundServiceOnObservableSchedule : BackgroundService | |
{ | |
private static readonly ILogger Logger = Log.ForContext<BackgroundServiceOnObservableSchedule>(); | |
private readonly IObservable<Unit> workerSequence; | |
private IDisposable workerSubscription; | |
public BackgroundServiceOnObservableSchedule() | |
{ | |
workerSequence = Observable | |
.Timer(TimeSpan.FromSeconds(5)) | |
.Do(_ => Logger.Information("Doing the work ...")) | |
.Select(_ => DoTheWork()) | |
.RetryWhen(errors => errors.SelectMany(ex => | |
{ | |
// This place is to filter on exception and log/throw/continue | |
Logger.Error(ex, $"Failure in {nameof(BackgroundServiceOnObservableSchedule)}"); | |
return Observable.Return(Unit.Default); | |
})) | |
.Repeat(); | |
} | |
private Unit DoTheWork() => Unit.Default; | |
protected override Task ExecuteAsync(CancellationToken stoppingToken) | |
{ | |
workerSubscription = workerSequence.Subscribe(_ => { }); | |
return Task.CompletedTask; | |
} | |
public override void Dispose() | |
{ | |
workerSubscription.Dispose(); | |
base.Dispose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment