scheduler.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. import time
  2. import requests
  3. import threading
  4. import urllib3
  5. from commons import err_log
  6. # 禁用SSL警告(https 自签名证书)
  7. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
  8. def _log(msg):
  9. print(f"[scheduler] {msg}")
  10. class CrawlerScheduler:
  11. """爬虫任务调度器"""
  12. def __init__(self, DEVICE_ID, platform, heartbeat_interval=30):
  13. """
  14. 初始化调度器
  15. Args:
  16. platform: 平台名称
  17. heartbeat_url: 心跳上报URL
  18. heartbeat_interval: 心跳间隔时间(秒)
  19. """
  20. self.username = DEVICE_ID
  21. self.platform = platform
  22. # 回告接口返回 code=error(如:该账号今日爬取量已达平台限额,任务已释放)
  23. # → 置位标志,采集主循环(step3)每批检查,立即停止采集
  24. self.limit_reached = False
  25. self.limit_msg = ""
  26. self._lock = threading.Lock()
  27. # ⭐ 必须用 https:http 会被 nginx 301 重定向,POST 会被降级成 GET 导致 405(美团同款坑)
  28. self.heartbeat_url = 'https://pricesys.kailin.com.cn:8082/api/collect_task/heartbeat'
  29. self.heartbeat_interval = heartbeat_interval
  30. self.end = False
  31. self.heartbeat_thread = None
  32. def _heartbeat_reporter(self):
  33. """守护线程:只负责上报心跳"""
  34. headers = {'X-Crawler-Token': 'zhijiayun_crawler_2026'}
  35. while True:
  36. try:
  37. json_data = {
  38. "platform": self.platform,
  39. "username": self.username
  40. }
  41. _log(f'上传心跳数据:{json_data},链接:{self.heartbeat_url}')
  42. response = requests.post(
  43. self.heartbeat_url,
  44. json=json_data,
  45. headers=headers,
  46. timeout=3,
  47. verify=False # 忽略SSL证书验证
  48. )
  49. print(f"[心跳] 发送成功: {response.status_code}")
  50. result = response.json()
  51. if self.end:
  52. break
  53. if result.get('code') != 'success':
  54. _log(f'心跳回传异常:{result}')
  55. else:
  56. _log(f'心跳回传:{result}')
  57. time.sleep(self.heartbeat_interval)
  58. except Exception as e:
  59. print(e)
  60. _log(e)
  61. time.sleep(5)
  62. def start(self):
  63. """启动调度器"""
  64. self.set_flag(False)
  65. if self.heartbeat_thread and self.heartbeat_thread.is_alive():
  66. return
  67. self.heartbeat_thread = threading.Thread(
  68. target=self._heartbeat_reporter,
  69. daemon=True
  70. )
  71. self.heartbeat_thread.start()
  72. def stop(self):
  73. """停止调度器"""
  74. self.set_flag(True)
  75. _log('心跳停止')
  76. def get_task(self):
  77. try:
  78. # ⭐ 必须用 https(原因同上:http 会被 301 重定向降级)
  79. task_api = "https://pricesys.kailin.com.cn:8082/api/collect_task/pull"
  80. headers = {'X-Crawler-Token': 'zhijiayun_crawler_2026'}
  81. params = {
  82. 'platform': self.platform,
  83. 'username': self.username
  84. }
  85. _log(f'拉取任务参数:{params},链接:{task_api}')
  86. response = requests.get(task_api, params=params, headers=headers, timeout=10, verify=False)
  87. result = response.json()
  88. _log(f'拉取任务:{result}')
  89. if result.get('code') == 'success':
  90. return result.get('data').get('task')
  91. print('拉取任务返回', result)
  92. except Exception as e:
  93. _log('获取任务报错', e)
  94. err_log.log_error(self.username, "pull_task_error", exc=e)
  95. def post_report(self, data):
  96. try:
  97. # ⭐ 必须用 https(原因同上:http 会被 301 重定向降级)
  98. url = "https://pricesys.kailin.com.cn:8082/api/collect_task/report"
  99. print('传给返回接口的数据', data)
  100. _log(f'report上传数据:{data},链接:{url}')
  101. headers = {'X-Crawler-Token': 'zhijiayun_crawler_2026'}
  102. response = requests.post(url, json=data, headers=headers, timeout=5, verify=False)
  103. # 记录日志
  104. result = response.json()
  105. _log(f"report回传数据{result}")
  106. if (result.get('code') != 'success'):
  107. _log(f'翻页回传结果不成功:{result}')
  108. self.stop()
  109. if result.get('code') == 'error':
  110. # 平台限额/任务已释放等错误 → 置位标志,采集主循环立即停止
  111. self.limit_msg = str(result.get('msg', ''))
  112. self.limit_reached = True
  113. _log(f'回告返回error,置位停止采集标志:{self.limit_msg}')
  114. print(f'任务进度上传 {result}')
  115. except Exception as e:
  116. _log(e)
  117. err_log.log_error(self.username, "report_error", exc=e,
  118. extra={"report": {k: data.get(k) for k in ("task_id", "is_finished", "need_reassign", "current_page", "crawled_count") if isinstance(data, dict)}})
  119. def set_flag(self, value):
  120. with self._lock:
  121. self.end = value