HeartBeatCheckJob.cs 2.3 KB

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