HeartBeatCheckJob.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using EVCB_OCPP.Domain;
  2. using EVCB_OCPP.Domain.Models.Database;
  3. using Microsoft.EntityFrameworkCore;
  4. using Microsoft.Extensions.Logging;
  5. using OCPPServer.Protocol;
  6. using Quartz;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Diagnostics;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. namespace EVCB_OCPP.WSServer.Jobs;
  14. [DisallowConcurrentExecution]
  15. public class HeartBeatCheckJob : IJob
  16. {
  17. public HeartBeatCheckJob(
  18. ProtalServer protalServer,
  19. IDbContextFactory<MainDBContext> maindbContextFactory,
  20. ILogger<HeartBeatCheckJob> logger)
  21. {
  22. this.protalServer = protalServer;
  23. this.maindbContextFactory = maindbContextFactory;
  24. this.logger = logger;
  25. }
  26. private readonly ProtalServer protalServer;
  27. private readonly IDbContextFactory<MainDBContext> maindbContextFactory;
  28. private readonly ILogger<HeartBeatCheckJob> logger;
  29. public async Task Execute(IJobExecutionContext context)
  30. {
  31. logger.LogDebug("{0} Started", nameof(HeartBeatCheckJob));
  32. try
  33. {
  34. Stopwatch watch = new Stopwatch();
  35. Dictionary<string, ClientData> _copyClientDic = protalServer.ClientDic;
  36. var cdt = DateTime.UtcNow;
  37. var clients = _copyClientDic.Where(x => x.Value.LastActiveTime > cdt.AddSeconds(-120)).Select(x => x.Value).ToList();
  38. watch.Start();
  39. foreach (var session in clients)
  40. {
  41. using (var db = await maindbContextFactory.CreateDbContextAsync())
  42. {
  43. var machine = new Machine() { Id = session.MachineId };
  44. if (machine != null)
  45. {
  46. //db.Configuration.AutoDetectChangesEnabled = false;
  47. //db.Configuration.ValidateOnSaveEnabled = false;
  48. db.Machine.Attach(machine);
  49. machine.HeartbeatUpdatedOn = DateTime.UtcNow;
  50. machine.ConnectionType = session.UriScheme.Equals("wss") ? 2 : 1;
  51. db.Entry(machine).Property(x => x.HeartbeatUpdatedOn).IsModified = true;
  52. db.Entry(machine).Property(x => x.ConnectionType).IsModified = true;
  53. await db.SaveChangesAsync();
  54. }
  55. }
  56. }
  57. watch.Stop();
  58. if (watch.ElapsedMilliseconds / 1000 > 5)
  59. {
  60. logger.LogCritical("Update HeartBeatCheckTrigger cost " + watch.ElapsedMilliseconds / 1000 + " seconds.");
  61. }
  62. }
  63. catch (Exception ex)
  64. {
  65. Console.WriteLine("***********************************************************");
  66. logger.LogError(string.Format("HeartBeatCheckTrigger Ex:{0}", ex.ToString()));
  67. }
  68. }
  69. }