using Quartz; using Sufi.Demo.PeopleDirectory.Application.Contracts.Repositories; using Sufi.Demo.PeopleDirectory.Application.Contracts.Services; using Sufi.Demo.PeopleDirectory.Domain.Entities.Misc; namespace Sufi.Demo.PeopleDirectory.Infrastructure.Jobs { /// /// Represents the cleanup job. /// /// /// Initialize an instance of class. /// /// /// public class ClearPersistentDataJob(IUnitOfWork unitOfWorkInt, IUnitOfWork unitOfWorkString, IAppCache appCache) : IJob { private const string LastDateDeletedKey = "LastDateDeleted"; private const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss.ffff"; /// /// Job implementation to be executed. /// /// /// public async Task Execute(IJobExecutionContext context) { // Get all contacts to be deleted. var contactsToDelete = await unitOfWorkInt.Repository().GetAllAsync(); // Skips if nothing to delete. if (contactsToDelete.Count == 0) return; // Delete all contacts. foreach (var contact in contactsToDelete) { await unitOfWorkInt.Repository().DeleteAsync(contact); } // Update the last date deleted in the ServerInfo table. var infoToUpdate = await unitOfWorkString.Repository().GetByIdAsync(LastDateDeletedKey); if (infoToUpdate != null) { infoToUpdate.Value = DateTime.UtcNow.ToString(DateTimeFormat); await unitOfWorkString.Repository().UpdateAsync(infoToUpdate); } else { var infoToAdd = new ServerInfo { Id = LastDateDeletedKey, Value = DateTime.UtcNow.ToString(DateTimeFormat) }; await unitOfWorkString.Repository().AddAsync(infoToAdd); } // Commit the changes to the database. await unitOfWorkString.Commit(context.CancellationToken); // Clear cache entries related to contacts. await appCache.ResetAsync(); } } }