ResultfulApiJob.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using IMCS.CCS.Entitys;
  2. using Microsoft.Extensions.Logging;
  3. using Quartz;
  4. using System;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. namespace IMCS.CCS.Service.Jobs
  9. {
  10. /// <summary>
  11. /// Resultful 风格 Api Job
  12. /// </summary>
  13. [DisallowConcurrentExecution]
  14. public class ResultfulApiJob : IJob
  15. {
  16. private readonly IApiRequestService _apiRequestService;
  17. private readonly ITaskService _taskService;
  18. private readonly ILogger<ResultfulApiJob> _logger;
  19. private readonly IJobLoggerService _jobLogger;
  20. public ResultfulApiJob(IApiRequestService apiRequestService, ITaskService taskService, ILogger<ResultfulApiJob> logger, IJobLoggerService jobLogger)
  21. {
  22. _apiRequestService = apiRequestService;
  23. _taskService = taskService;
  24. _logger = logger;
  25. _jobLogger = jobLogger;
  26. }
  27. public async Task Execute(IJobExecutionContext context)
  28. {
  29. try
  30. {
  31. Stopwatch _stopwatch = new Stopwatch();
  32. _stopwatch.Restart();
  33. var tasksId = context.MergedJobDataMap.GetString("TasksId")?.ToString();
  34. if (string.IsNullOrWhiteSpace(tasksId))
  35. {
  36. _logger.LogError("tasksId 空!");
  37. return;
  38. }
  39. var tasks = await _taskService.FindByIdAsync(Guid.Parse(tasksId));
  40. if (tasks == null)
  41. {
  42. _logger.LogError("tasks 空!");
  43. return;
  44. }
  45. //运行开始记录
  46. //_jobLogger.Write(new JobLoggerInfo()
  47. //{
  48. // Id = Guid.NewGuid(),
  49. // TasksId = tasks.Id ?? Guid.Empty,
  50. // Text = $"[执行任务Start] Id={tasks.Id}、Name={tasks.Name}、GroupName={tasks.GroupName}",
  51. // CreateTime = DateTime.Now
  52. //});
  53. var time = DateTime.Now;
  54. var taskId = tasks?.Id ?? Guid.Empty;
  55. var result = await _apiRequestService.RequestAsync(tasks.RequsetMode, tasks.ApiUrl, null, tasks.HeaderToken);
  56. if (result.IsSuccess)
  57. {
  58. await _taskService.UpdateExecuteTime(taskId, time);
  59. }
  60. else
  61. {
  62. // _logger.LogError($"Web Api RequestAsync(); 请求失败! WebApi 返回结果:{result.Message}");
  63. }
  64. _stopwatch.Stop();
  65. //运行结束记录
  66. var text = $"{time.ToString("yyyy-MM-dd HH:mm:ss:fff")} [{tasks.Name} 耗时:{_stopwatch.ElapsedMilliseconds} 毫秒]";
  67. text += $" 分组 = {tasks.GroupName}、";
  68. text += $"结果 = {result.Message}";
  69. _jobLogger.Write(new JobLoggerInfo()
  70. {
  71. Id = Guid.NewGuid(),
  72. TasksId = taskId,
  73. Text = text,
  74. CreateTime = time
  75. });
  76. }
  77. catch (Exception ex)
  78. {
  79. var message = $@"Message={ex.Message}\r\n
  80. StackTrace={ex.StackTrace}\r\n
  81. Source={ex.Source}\r\n";
  82. _logger.LogError(ex, message, null);
  83. }
  84. }
  85. }
  86. }