DocSpace-buildtools/common/services/ASC.Notify/NotifyCleaner.cs

63 lines
2.1 KiB
C#
Raw Normal View History

2022-02-21 12:28:52 +00:00
namespace ASC.Notify;
2022-02-16 13:14:31 +00:00
[Singletone]
2022-02-21 12:28:52 +00:00
public class NotifyCleaner : BackgroundService
2020-10-19 15:53:15 +00:00
{
2022-02-16 13:14:31 +00:00
private readonly ILog _logger;
2022-02-21 12:28:52 +00:00
private readonly NotifyServiceCfg _notifyServiceCfg;
private readonly IServiceScopeFactory _serviceScopeFactory;
2022-02-21 12:28:52 +00:00
private readonly TimeSpan _waitingPeriod = TimeSpan.FromHours(8);
2022-02-16 13:14:31 +00:00
public NotifyCleaner(IOptions<NotifyServiceCfg> notifyServiceCfg, IServiceScopeFactory serviceScopeFactory, IOptionsMonitor<ILog> options)
2022-02-16 13:14:31 +00:00
{
2022-02-21 12:28:52 +00:00
_logger = options.Get("ASC.NotifyCleaner");
_notifyServiceCfg = notifyServiceCfg.Value;
_serviceScopeFactory = serviceScopeFactory;
2022-02-16 13:14:31 +00:00
}
2022-02-21 12:28:52 +00:00
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
2022-02-16 13:14:31 +00:00
{
2022-02-21 12:28:52 +00:00
_logger.Info("Notify Cleaner Service running.");
2022-02-16 13:14:31 +00:00
2022-02-21 12:28:52 +00:00
while (!stoppingToken.IsCancellationRequested)
{
Clear();
await Task.Delay(_waitingPeriod, stoppingToken);
}
_logger.Info("Notify Cleaner Service is stopping.");
2022-02-16 13:14:31 +00:00
}
2020-11-20 12:49:57 +00:00
2022-02-16 13:14:31 +00:00
private void Clear()
{
2022-02-21 12:28:52 +00:00
try
2020-11-20 12:49:57 +00:00
{
2022-02-21 12:28:52 +00:00
var date = DateTime.UtcNow.AddDays(-_notifyServiceCfg.StoreMessagesDays);
2022-02-16 13:14:31 +00:00
2022-02-21 12:28:52 +00:00
using var scope = _serviceScopeFactory.CreateScope();
using var dbContext = scope.ServiceProvider.GetService<DbContextManager<NotifyDbContext>>().Get(_notifyServiceCfg.ConnectionStringName);
using var tx = dbContext.Database.BeginTransaction();
2022-02-16 13:14:31 +00:00
2022-02-21 12:28:52 +00:00
var info = dbContext.NotifyInfo.Where(r => r.ModifyDate < date && r.State == 4).ToList();
var queue = dbContext.NotifyQueue.Where(r => r.CreationDate < date).ToList();
dbContext.NotifyInfo.RemoveRange(info);
dbContext.NotifyQueue.RemoveRange(queue);
2022-02-16 13:14:31 +00:00
2022-02-21 12:28:52 +00:00
dbContext.SaveChanges();
tx.Commit();
2022-02-16 13:14:31 +00:00
2022-02-21 12:28:52 +00:00
_logger.InfoFormat("Clear notify messages: notify_info({0}), notify_queue ({1})", info.Count, queue.Count);
2022-02-16 13:14:31 +00:00
}
2022-02-21 12:28:52 +00:00
catch (ThreadAbortException)
{
// ignore
}
catch (Exception err)
2022-02-16 13:14:31 +00:00
{
2022-02-21 12:28:52 +00:00
_logger.Error(err);
2020-11-20 12:49:57 +00:00
}
2022-02-16 13:14:31 +00:00
}
2022-02-21 12:28:52 +00:00
}