diff --git a/src/Api/ConfigureServices.cs b/src/Api/ConfigureServices.cs index 4c4f747f..632e6ef5 100644 --- a/src/Api/ConfigureServices.cs +++ b/src/Api/ConfigureServices.cs @@ -14,7 +14,7 @@ public static IServiceCollection AddApiServices(this IServiceCollection services { // Register services services.AddServices(); - + services.AddBackgroundServices(); services.AddControllers(opt => opt.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()))); @@ -59,4 +59,11 @@ private static IServiceCollection AddServices(this IServiceCollection services) return services; } + + private static IServiceCollection AddBackgroundServices(this IServiceCollection services) + { + services.AddHostedService(); + + return services; + } } \ No newline at end of file diff --git a/src/Api/Services/BorrowRequestService.cs b/src/Api/Services/BorrowRequestService.cs new file mode 100644 index 00000000..fc436b12 --- /dev/null +++ b/src/Api/Services/BorrowRequestService.cs @@ -0,0 +1,43 @@ +using Application.Common.Interfaces; +using Domain.Statuses; +using Infrastructure.Persistence; +using NodaTime; + +namespace Api.Services; + +public class BorrowRequestService : BackgroundService +{ + private readonly IServiceProvider _serviceProvider; + + public BorrowRequestService(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + + while (!stoppingToken.IsCancellationRequested) + { + using (var scope = _serviceProvider.CreateScope()) + { + var localDateTimeNow = LocalDateTime.FromDateTime(DateTime.Now); + var context = scope.ServiceProvider.GetRequiredService(); + var overdueRequests = context.Borrows + .Where(x => x.Status != BorrowRequestStatus.Overdue + && x.Status == BorrowRequestStatus.CheckedOut + && x.DueTime < localDateTimeNow) + .ToList(); + + foreach (var request in overdueRequests) + { + request.Status = BorrowRequestStatus.Overdue; + } + context.UpdateRange(overdueRequests); + + await context.SaveChangesAsync(stoppingToken); + await Task.Delay(TimeSpan.FromMinutes(2), stoppingToken); + } + } + } +} \ No newline at end of file