Skip to content

Instantly share code, notes, and snippets.

@Nercury
Created September 13, 2021 09:14
Show Gist options
  • Save Nercury/6b690446bbd40f6971856adf322bfcbf to your computer and use it in GitHub Desktop.
Save Nercury/6b690446bbd40f6971856adf322bfcbf to your computer and use it in GitHub Desktop.
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