Skip to content

Commit

Permalink
Add record cleanup service.
Browse files Browse the repository at this point in the history
  • Loading branch information
bitbound committed Apr 30, 2020
1 parent e5c78ef commit a6f2acf
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
51 changes: 51 additions & 0 deletions Server/Services/CleanupService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Remotely.Server.Services
{
public class CleanupService : IHostedService, IDisposable
{
public CleanupService(IServiceProvider serviceProvider)
{
Services = serviceProvider;
}

private IServiceProvider Services { get; }
private System.Timers.Timer CleanupTimer { get; set; }

public void Dispose()
{
CleanupTimer?.Dispose();
}

public Task StartAsync(CancellationToken cancellationToken)
{
CleanupTimer?.Dispose();
CleanupTimer = new System.Timers.Timer(TimeSpan.FromDays(1).TotalMilliseconds);
CleanupTimer.Elapsed += CleanupTimer_Elapsed;
CleanupTimer.Start();
return Task.CompletedTask;
}

public Task StopAsync(CancellationToken cancellationToken)
{
CleanupTimer?.Dispose();
return Task.CompletedTask;
}

private void CleanupTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
using (var scope = Services.CreateScope())
{
var dataService = scope.ServiceProvider.GetRequiredService<DataService>();

dataService.CleanupOldRecords();
}
}
}
}
1 change: 1 addition & 0 deletions Server/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ public void ConfigureServices(IServiceCollection services)
services.AddSingleton<ApplicationConfig>();
services.AddSingleton<RandomGenerator>();
services.AddScoped<ApiAuthorizationFilter>();
services.AddHostedService<CleanupService>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
Expand Down

0 comments on commit a6f2acf

Please sign in to comment.