blog3000/Blog3000/Server/MiddleWares/BlogPostRepoUpdater.cs

62 lines
1.5 KiB
C#

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Blog3000.Server
{
internal class BlogPostRepoUpdater : IHostedService, IDisposable
{
private readonly ILogger logger;
private readonly BlogPostRepo repo;
private Timer timer;
public BlogPostRepoUpdater(ILogger<BlogPostRepoUpdater> logger, BlogPostRepo repo)
{
this.logger = logger;
this.repo = repo;
}
public void Dispose()
{
timer?.Dispose();
}
public Task StartAsync(CancellationToken cancellationToken)
{
logger.LogInformation("BlogPostRepoUpdater Service starting...");
// Time so cache should never be expired, when a request comes in
timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5*60-30));
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
logger.LogInformation("BlogPostRepoUpdater Service stopping.");
timer?.Dispose();
timer = null;
return Task.CompletedTask;
}
private void DoWork(object state)
{
logger.LogInformation("BlogPostRepoUpdater updating BlogPostRepo");
repo.UpdateCache();
}
}
}