Job_HttpRequest.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using Infrastructure;
  2. using Infrastructure.Attribute;
  3. using Quartz;
  4. using Quartz.Impl;
  5. using Quartz.Impl.Triggers;
  6. using System;
  7. using System.Threading.Tasks;
  8. using ZR.Service.System.IService;
  9. namespace ZR.Tasks.TaskScheduler
  10. {
  11. /// <summary>
  12. /// 定时任务http请求
  13. /// </summary>
  14. [AppService(ServiceType = typeof(Job_HttpRequest), ServiceLifetime = LifeTime.Scoped)]
  15. internal class Job_HttpRequest : JobBase, IJob
  16. {
  17. private readonly ISysTasksQzService tasksQzService;
  18. private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
  19. public Job_HttpRequest(ISysTasksQzService tasksQzService)
  20. {
  21. this.tasksQzService = tasksQzService;
  22. }
  23. public async Task Execute(IJobExecutionContext context)
  24. {
  25. await ExecuteJob(context, async () => await Run(context));
  26. }
  27. public async Task Run(IJobExecutionContext context)
  28. {
  29. AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
  30. var info = await tasksQzService.GetByIdAsync(trigger.JobName);
  31. if (info == null)
  32. {
  33. throw new CustomException($"任务{trigger?.JobName}网络请求执行失败,任务不存在");
  34. }
  35. string result;
  36. if (info.RequestMethod != null && info.RequestMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
  37. {
  38. result = await HttpHelper.HttpPostAsync(info.ApiUrl, info.JobParams);
  39. }
  40. else
  41. {
  42. var url = info.ApiUrl;
  43. if (url.IndexOf("?") > -1)
  44. {
  45. url += "&" + info.JobParams;
  46. }
  47. else
  48. {
  49. url += "?" + info.JobParams;
  50. }
  51. result = await HttpHelper.HttpGetAsync(url);
  52. }
  53. logger.Info($"任务【{info.Name}】网络请求执行结果=" + result);
  54. }
  55. }
  56. }