Created
November 8, 2019 12:36
-
-
Save spixy/28d82b79727a06d8cd3a10af57ea0680 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
/// <summary> | |
/// Hosted service base class | |
/// </summary> | |
public abstract class HostedServiceBase : IHostedService, IDisposable | |
{ | |
private readonly TimeSpan dueTime; | |
private readonly TimeSpan period; | |
private Timer timer; | |
/// <summary> | |
/// Service provider | |
/// </summary> | |
protected IServiceProvider Services { get; } | |
protected HostedServiceBase(IServiceProvider services, TimeSpan dueTime, TimeSpan period) | |
{ | |
Services = services; | |
this.dueTime = dueTime; | |
this.period = period; | |
} | |
/// <summary> | |
/// Background worker task | |
/// </summary> | |
protected abstract Task DoWork(); | |
/// <inheritdoc cref="IHostedService.StartAsync"/> | |
public Task StartAsync(CancellationToken cancellationToken) | |
{ | |
// RollbarLocator.RollbarInstance.Info($"{GetType().Name} started."); | |
timer = new Timer(DoWork, null, dueTime, period); | |
return Task.CompletedTask; | |
} | |
/// <summary> | |
/// Timer update loop | |
/// </summary> | |
private async void DoWork(object state) | |
{ | |
// RollbarLocator.RollbarInstance.Info($"{GetType().Name} DoWork."); | |
try | |
{ | |
await DoWork(); | |
} | |
catch (Exception e) | |
{ | |
RollbarLocator.RollbarInstance.Error(e); | |
} | |
} | |
/// <inheritdoc cref="IHostedService.StopAsync"/> | |
public Task StopAsync(CancellationToken cancellationToken) | |
{ | |
// RollbarLocator.RollbarInstance.Info($"{GetType().Name} stopped."); | |
timer?.Change(Timeout.Infinite, 0); | |
return Task.CompletedTask; | |
} | |
/// <inheritdoc cref="IDisposable.Dispose" /> | |
public void Dispose() | |
{ | |
timer?.Dispose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment