Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vcaraulean/56b6a49bf55485da9651fb6dbd1dfa51 to your computer and use it in GitHub Desktop.
Save vcaraulean/56b6a49bf55485da9651fb6dbd1dfa51 to your computer and use it in GitHub Desktop.
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