task_scheduler.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import asyncio
  2. import time
  3. from datetime import datetime
  4. from applications.api import feishu_robot
  5. from applications.utils import task_schedule_response
  6. from applications.tasks.monitor_tasks import check_kimi_balance
  7. from applications.tasks.monitor_tasks import GetOffVideos
  8. from applications.tasks.monitor_tasks import CheckVideoAuditStatus
  9. class TaskScheduler:
  10. def __init__(self, data, log_service, db_client):
  11. self.data = data
  12. self.log_client = log_service
  13. self.db_client = db_client
  14. self.table = "long_articles_task_manager"
  15. async def whether_task_processing(self, task_name: str) -> bool:
  16. """whether task is processing"""
  17. query = f"""
  18. select start_timestamp from {self.table} where task_name = %s and task_status = %s;
  19. """
  20. response, error = await self.db_client.async_fetch(
  21. query=query, params=(task_name, 1)
  22. )
  23. if not response:
  24. # no task is processing
  25. return False
  26. else:
  27. start_timestamp = response[0]["start_timestamp"]
  28. # todo: every task should has a unique expire timestamp, remember to write that in a task config file
  29. if int(time.time()) - start_timestamp >= 86400:
  30. await feishu_robot.bot(
  31. title=f"{task_name} has been processing for more than one day",
  32. detail={"timestamp": start_timestamp},
  33. env="long_articles_task",
  34. )
  35. return True
  36. async def record_task(self, task_name, date_string):
  37. """record task"""
  38. query = f"""insert into {self.table} (date_string, task_name, start_timestamp) values (%s, %s, %s);"""
  39. await self.db_client.async_save(
  40. query=query, params=(date_string, task_name, int(time.time()))
  41. )
  42. async def lock_task(self, task_name, date_string):
  43. query = f"""update {self.table} set task_status = %s where task_name = %s and date_string = %s and task_status = %s;"""
  44. return await self.db_client.async_save(
  45. query=query, params=(1, task_name, date_string, 0)
  46. )
  47. async def release_task(self, task_name, date_string, final_status):
  48. """
  49. 任务执行完成之后,将任务状态设置为完成状态/失败状态
  50. """
  51. query = f"""
  52. update {self.table}
  53. set task_status = %s, finish_timestamp = %s
  54. where task_name = %s and date_string = %s and task_status = %s;
  55. """
  56. return await self.db_client.async_save(
  57. query=query,
  58. params=(final_status, int(time.time()), task_name, date_string, 1),
  59. )
  60. async def deal(self):
  61. task_name = self.data.get("task_name")
  62. date_string = self.data.get("date_string")
  63. if not task_name:
  64. await self.log_client.log(
  65. contents={
  66. "task": task_name,
  67. "function": "task_scheduler_deal",
  68. "message": "not task name in params",
  69. "status": "fail",
  70. "data": self.data,
  71. }
  72. )
  73. return await task_schedule_response.fail_response(
  74. error_code="4002", error_message="task_name must be input"
  75. )
  76. if not date_string:
  77. date_string = datetime.today().strftime("%Y-%m-%d")
  78. # prepare for task
  79. if await self.whether_task_processing(task_name):
  80. return await task_schedule_response.fail_response(
  81. error_code="5001", error_message="task is processing"
  82. )
  83. await self.record_task(task_name=task_name, date_string=date_string)
  84. await self.lock_task(task_name, date_string)
  85. match task_name:
  86. case "check_kimi_balance":
  87. response = await check_kimi_balance()
  88. await self.log_client.log(
  89. contents={
  90. "task": task_name,
  91. "function": "task_scheduler_deal",
  92. "message": "check_kimi_balance task execute successfully",
  93. "status": "success",
  94. "data": response,
  95. }
  96. )
  97. return await task_schedule_response.success_response(
  98. task_name=task_name, data=response
  99. )
  100. case "get_off_videos":
  101. async def background_get_off_videos():
  102. sub_task = GetOffVideos(self.db_client, self.log_client)
  103. await sub_task.get_off_job()
  104. task_status = await sub_task.check()
  105. await self.release_task(
  106. task_name=task_name,
  107. date_string=date_string,
  108. final_status=task_status,
  109. )
  110. asyncio.create_task(background_get_off_videos())
  111. return await task_schedule_response.success_response(
  112. task_name=task_name,
  113. data={"code": 0, "message": "get off_videos started background"},
  114. )
  115. case "check_publish_video_audit_status":
  116. async def background_check_publish_video_audit_status():
  117. sub_task = CheckVideoAuditStatus(self.db_client, self.log_client)
  118. print("start processing task status: ")
  119. task_status = await sub_task.deal()
  120. await self.release_task(
  121. task_name=task_name,
  122. date_string=date_string,
  123. final_status=task_status,
  124. )
  125. print("finish task status: ", task_status)
  126. asyncio.create_task(background_check_publish_video_audit_status())
  127. return await task_schedule_response.success_response(
  128. task_name=task_name,
  129. data={
  130. "code": 0,
  131. "message": "check publish video audit status started",
  132. },
  133. )
  134. case _:
  135. await self.log_client.log(
  136. contents={
  137. "task": task_name,
  138. "function": "task_scheduler_deal",
  139. "message": "wrong task input",
  140. "status": "success",
  141. "data": self.data,
  142. }
  143. )
  144. await self.release_task(task_name, date_string, 99)
  145. return await task_schedule_response.fail_response(
  146. error_code="4001", error_message="wrong task name input"
  147. )