Created
September 13, 2021 09:14
-
-
Save Nercury/6b690446bbd40f6971856adf322bfcbf 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; | |
namespace BackgroundUpdate | |
{ | |
public class UpdateRunner<T>: IHostedService, IDisposable where T: IUpdate | |
{ | |
private readonly T _inner; | |
private readonly TimeSpan _period; | |
private Timer? _timer; | |
public UpdateRunner(T inner, TimeSpan period) | |
{ | |
_inner = inner; | |
_period = period; | |
} | |
public Task StartAsync(CancellationToken cancellationToken) | |
{ | |
_timer = new Timer(async _ => await _inner.Update(), null, TimeSpan.FromSeconds(1), _period); | |
return Task.CompletedTask; | |
} | |
public Task StopAsync(CancellationToken cancellationToken) | |
{ | |
_timer?.Change(Timeout.Infinite, 0); | |
return Task.CompletedTask; | |
} | |
public void Dispose() | |
{ | |
_timer?.Dispose(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment