using Microsoft.EntityFrameworkCore; using vendorApproverBackend.Data; public class CertificationExpiryJob : CronJobService { private readonly IServiceProvider _serviceProvider; // The cron expression: "0 0 * * *" means "At 00:00 every day" private const string CronSchedule = "0 0 * * *"; // Use UTC or the specific TimeZone where the midnight check should happen public CertificationExpiryJob(IServiceProvider serviceProvider) : base(CronSchedule, TimeZoneInfo.Utc) { _serviceProvider = serviceProvider; } protected override async Task ExecuteAsync(CancellationToken cancellationToken) { Console.WriteLine($"Certification Expiry Job started at {DateTime.UtcNow} UTC."); using (var scope = _serviceProvider.CreateScope()) { var context = scope.ServiceProvider.GetRequiredService(); var todayUtcStart = DateTime.UtcNow.Date; var certificatesToExpire = await context.Certifications .Where(c => c.Status == CertificationStatus.ACTIVE) .Where(c => c.ExpiryDate.Date <= todayUtcStart) .ToListAsync(cancellationToken); if (certificatesToExpire.Any()) { Console.WriteLine($"Found {certificatesToExpire.Count} certifications to expire."); foreach (var cert in certificatesToExpire) { cert.Status = CertificationStatus.EXPIRED; } context.Certifications.UpdateRange(certificatesToExpire); await context.SaveChangesAsync(cancellationToken); Console.WriteLine("Certifications successfully expired."); } else { Console.WriteLine("No certifications found to expire."); } } } }