IESTimerTrigger.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. using System;
  2. using DinkToPdf.Contracts;
  3. using Microsoft.Azure.Functions.Worker;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.Logging;
  6. using TEAMModelOS.SDK.DI;
  7. using TEAMModelOS.SDK;
  8. using TEAMModelOS.SDK.Extension;
  9. using TEAMModelOS.SDK.Models.Service.BI;
  10. using System.Globalization;
  11. using TEAMModelOS.SDK.Models;
  12. using HTEX.Lib.ETL.Lesson;
  13. using System.Linq;
  14. using TEAMModelOS.SDK.DI.IPIP;
  15. using static TEAMModelOS.SDK.Extension.GeoRegion;
  16. using System.Text.Json;
  17. namespace TEAMModelOS.Function
  18. {
  19. public class IESTimerTrigger
  20. {
  21. private readonly ILogger _logger;
  22. /// <summary>
  23. /// 文档。https://docs.microsoft.com/zh-cn/azure/azure-functions/functions-bindings-timer?tabs=in-process&pivots=programming-language-csharp
  24. /// Timer 在线测试 https://ncrontab.swimburger.net/
  25. /// </summary>
  26. private readonly AzureCosmosFactory _azureCosmos;
  27. private readonly DingDing _dingDing;
  28. private readonly AzureStorageFactory _azureStorage;
  29. private readonly AzureRedisFactory _azureRedis;
  30. //private readonly IConverter _converter;
  31. private readonly SnowflakeId _snowflakeId;
  32. private readonly IHttpClientFactory _httpClient;
  33. private readonly CoreAPIHttpService _coreAPIHttpService;
  34. //private IPSearcher _ipSearcher;
  35. private readonly IConfiguration _configuration;
  36. private readonly City _city;
  37. public IESTimerTrigger(ILoggerFactory loggerFactory, IConfiguration configuration, CoreAPIHttpService coreAPIHttpService, IHttpClientFactory httpClient, SnowflakeId snowflakeId, AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, City city)
  38. {
  39. _logger = loggerFactory.CreateLogger<IESTimerTrigger>();
  40. _azureCosmos = azureCosmos;
  41. _dingDing = dingDing;
  42. _azureStorage = azureStorage;
  43. _azureRedis = azureRedis;
  44. // _converter = converter;
  45. _snowflakeId=snowflakeId;
  46. _httpClient = httpClient;
  47. // _ipSearcher = ipSearcher;
  48. _coreAPIHttpService = coreAPIHttpService;
  49. _configuration= configuration;
  50. _city = city;
  51. }
  52. //0 0 20 * * 0
  53. [Function("WeeklyReport")]
  54. public async Task WeeklyReport([TimerTrigger("0 0 20 * * 0")] TimerInfo myTimer)
  55. {
  56. await TEAMModelOS.SDK.Models.Service.SystemService.LessonWeekly(_azureRedis,_azureCosmos,_coreAPIHttpService,_dingDing,_configuration);
  57. //var server = _azureRedis.GetGetServer();
  58. //// 使用Keys方法获取所有匹配前缀的key
  59. //var pattern = "LessonWeek:*";
  60. //var keys = server.Keys(8, pattern);
  61. //foreach (var key in keys)
  62. //{
  63. // await _azureRedis.GetRedisClient(8).KeyDeleteAsync(key);
  64. //}
  65. }
  66. /// <summary>
  67. /// //0 1 * * * * 一天中每小时的第 1 分钟
  68. ///0 */10 * * * * 每五分钟一次
  69. /// </summary>
  70. /// <param name="myTimer"></param>
  71. /// <returns></returns>
  72. [Function("DailyReport")]
  73. public async Task DailyReport([TimerTrigger("0 1 * * * *")] TimerInfo myTimer)
  74. {
  75. _logger.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
  76. try
  77. {
  78. await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.location},定时任务{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss")}", GroupNames.成都开发測試群組);
  79. string? local = Environment.GetEnvironmentVariable("Option:Location");
  80. // if (local.Contains("Test")||local.Contains("Dep"))
  81. {
  82. int am = 8;
  83. int pm = 20;
  84. //int am = DateTimeOffset.Now.Hour;
  85. //int pm = DateTimeOffset.Now.Hour;
  86. var url = Environment.GetEnvironmentVariable("HaBookAuth:CoreAPI");
  87. var clientID = Environment.GetEnvironmentVariable("HaBookAuth:CoreService:clientID");
  88. var clientSecret = Environment.GetEnvironmentVariable("HaBookAuth:CoreService:clientSecret");
  89. string location = "";
  90. if (local!.Contains("China"))
  91. {
  92. location = "China";
  93. return;
  94. }
  95. else if (local.Contains("Global"))
  96. {
  97. location = "Global";
  98. }
  99. var client = _httpClient.CreateClient();
  100. var token = CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, location).Result;
  101. if (client.DefaultRequestHeaders.Contains("Authorization"))
  102. {
  103. client.DefaultRequestHeaders.Remove("Authorization");
  104. client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  105. }
  106. else
  107. {
  108. client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  109. }
  110. var data = await TEAMModelOS.SDK.Models.Service.SystemService.AccumulateDaily(_configuration, _azureRedis, _azureCosmos,_azureStorage, _coreAPIHttpService, _dingDing, client, _snowflakeId, url, am, pm);
  111. //await _dingDing.SendBotMsg($"返回数据{data.ToJsonString()}", GroupNames.成都开发測試群組);
  112. }
  113. }
  114. catch (Exception ex)
  115. {
  116. await _dingDing.SendBotMsg($"{DailyReport}\n{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  117. }
  118. if (myTimer.ScheduleStatus is not null)
  119. {
  120. _logger.LogInformation($"Next timer schedule at: {myTimer.ScheduleStatus.Next}");
  121. }
  122. }
  123. /// <summary>
  124. /// 每天執行 取得IOT TeachingData 並統計昨日每校Redis資料 執行時間:每日凌晨1時1分
  125. /// </summary>
  126. [Function("BICrtDailyAnal")]
  127. //0 1 0 * * * 一天中00的第 1 分钟
  128. //0 1 * * * * 一天中每小时的第 1 分钟
  129. //0 */10 * * * * 每五分钟一次
  130. public async Task BICreatDailyAnalData([TimerTrigger("0 1 1 * * *")] TimerInfo myTimer, ILogger log)
  131. {
  132. var _azureCosmosClient = _azureCosmos.GetCosmosClient();
  133. var _azureCosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
  134. var _azureCosmosClientCsv2CnRead = _azureCosmos.GetCosmosClient(name: "CoreServiceV2CnRead");
  135. var datetime = DateTimeOffset.UtcNow.AddHours(-12); //統計昨天的數據
  136. var y = $"{datetime.Year}";
  137. var m = datetime.Month >= 10 ? $"{datetime.Month}" : $"0{datetime.Month}";
  138. var d = datetime.Day >= 10 ? $"{datetime.Day}" : $"0{datetime.Day}";
  139. string? local = Environment.GetEnvironmentVariable("Option:Location");
  140. List<regionrow> region_gl = new List<regionrow>();
  141. using (StreamReader r = new StreamReader("JsonFile/Region/region_gl.json"))
  142. {
  143. string json_g = r.ReadToEnd();
  144. region_gl = JsonSerializer.Deserialize<List<regionrow>>(json_g);
  145. }
  146. List<regionrow> region_cn = new List<regionrow>();
  147. using (StreamReader r = new StreamReader("JsonFile/Region/region_cn.json"))
  148. {
  149. string json_c = r.ReadToEnd();
  150. region_cn = JsonSerializer.Deserialize<List<regionrow>>(json_c);
  151. }
  152. //生成學校IOT數據
  153. await BIProdAnalysis.BICreatDailyAnalData(_azureRedis, _azureCosmosClient, _azureCosmosClientCsv2, _azureCosmosClientCsv2CnRead, _dingDing, _city, local, y, m, d, region_gl, region_cn);
  154. //刪除三個月以前的Redis數據 [待做]
  155. }
  156. }
  157. }