scheduler.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. import time
  2. import requests
  3. from commons.Logger import get_spider_logger
  4. import threading
  5. logger = get_spider_logger('scheduler')
  6. class CrawlerScheduler:
  7. """爬虫任务调度器"""
  8. def __init__(self, DEVICE_ID, platform, heartbeat_interval=30):
  9. """
  10. 初始化调度器
  11. Args:
  12. platform: 平台名称
  13. heartbeat_url: 心跳上报URL
  14. heartbeat_interval: 心跳间隔时间(秒)
  15. """
  16. self.username = DEVICE_ID
  17. self.platform = platform
  18. self._lock = threading.Lock()
  19. self.heartbeat_url = 'http://pricesys2.kailin.com.cn:8083/api/collect_task/heartbeat'
  20. self.heartbeat_interval = heartbeat_interval
  21. self.end = False
  22. self.heartbeat_thread = None
  23. def _heartbeat_reporter(self):
  24. """守护线程:只负责上报心跳"""
  25. headers = {'X-Crawler-Token': 'zhijiayun_crawler_2026'}
  26. while True:
  27. try:
  28. response = requests.post(
  29. self.heartbeat_url,
  30. json={
  31. "platform": self.platform,
  32. "username": self.username
  33. },
  34. headers=headers,
  35. timeout=3
  36. )
  37. print(f"[心跳] 发送成功: {response.status_code}")
  38. result = response.json()
  39. if self.end or result.get('code') != 'success':
  40. logger.error(f'心跳回传:{result}')
  41. self.set_flag(True)
  42. # 写日志
  43. break
  44. logger.info(f'心跳回传:{result}')
  45. self.set_flag(False)
  46. time.sleep(self.heartbeat_interval)
  47. except Exception as e:
  48. print(e)
  49. logger.error(e)
  50. time.sleep(5)
  51. def start(self):
  52. """启动调度器"""
  53. self.set_flag(False)
  54. if hasattr(self, 'heartbeat_thread') and self.heartbeat_thread and self.heartbeat_thread.is_alive():
  55. return
  56. self.heartbeat_thread = threading.Thread(
  57. target=self._heartbeat_reporter,
  58. daemon=True
  59. )
  60. self.heartbeat_thread.start()
  61. def stop(self):
  62. """停止调度器"""
  63. self.set_flag(True)
  64. logger.info('心跳停止')
  65. def get_task(self):
  66. try:
  67. task_api = "http://pricesys2.kailin.com.cn:8083/api/collect_task/pull"
  68. headers = {'X-Crawler-Token': 'zhijiayun_crawler_2026'}
  69. params = {
  70. 'platform': self.platform,
  71. 'username': self.username
  72. }
  73. response = requests.get(task_api, params=params, headers=headers, timeout=5)
  74. result = response.json()
  75. logger.info(f'拉取任务:{result}')
  76. if result.get('code') == 'success':
  77. return result.get('data').get('task')
  78. print('拉取任务返回', result)
  79. except Exception as e:
  80. logger.error('获取任务报错', e)
  81. def post_report(self, data):
  82. try:
  83. url = "http://pricesys2.kailin.com.cn:8083/api/collect_task/report"
  84. print('传给返回接口的数据', data)
  85. logger.info(f'report上传数据:{data}')
  86. headers = {'X-Crawler-Token': 'zhijiayun_crawler_2026'}
  87. response = requests.post(url, json=data, headers=headers, timeout=5)
  88. # 记录日志
  89. result = response.json()
  90. logger.info(result)
  91. if (result.get('code') != 'success'):
  92. logger.error(f'翻页回传结果不成功:{result}')
  93. self.stop()
  94. print(f'任务进度上传 {result}')
  95. except Exception as e:
  96. logger.error(e)
  97. def set_flag(self, value):
  98. with self._lock:
  99. self.end = value