using System; using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using AyaNova.Models; using AyaNova.Util; namespace AyaNova.Biz { /// /// Preventive maintenance generator /// turn PMs into Work orders /// /// internal static class CoreJobPMGenerate { private static bool IsRunning = false; private static ILogger log = AyaNova.Util.ApplicationLogging.CreateLogger("CoreJobPMGenerate"); private static DateTime lastRun = DateTime.MinValue; #if (DEBUG) private static TimeSpan RUN_EVERY_INTERVAL = new TimeSpan(0, 0, 24);//no more frequently than once every 20 seconds #else private static TimeSpan RUN_EVERY_INTERVAL = new TimeSpan(0, 5, 2);//no more frequently than once every 5 minutes #endif public static async Task DoWorkAsync() { log.LogTrace("Checking if PMGenerate should run"); if (IsRunning) { log.LogTrace("PMGenerate is running already exiting this cycle"); return; } //This will get triggered roughly every minute, but we don't want to deliver that frequently if (DateTime.UtcNow - lastRun < RUN_EVERY_INTERVAL) { log.LogTrace($"PMGenerate ran less than {RUN_EVERY_INTERVAL} ago, exiting this cycle"); return; } try { IsRunning = true; log.LogDebug("PMGenerate set to RUNNING state and starting now"); using (AyContext ct = AyaNova.Util.ServiceProviderProvider.DBContext) { await PMBiz.GenerateAsync(ct, log); } } catch (Exception ex) { log.LogError(ex, $"Error processing PMGenerate "); await NotifyEventHelper.AddGeneralNotifyEvent(NotifyEventType.PMGenerationFailed, "PM Generate failure","Preventive Maintenance", ex); } finally { log.LogDebug("PMGenerate has completed; setting to not running state and tagging lastRun timestamp"); lastRun = DateTime.UtcNow; IsRunning = false; } } ///////////////////////////////////////////////////////////////////// }//eoc }//eons