CeleryBeatObject.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. # @Author : Rocky
  2. # @File : CeleryBeatObject.py
  3. # @Time : 2024/3/21 16:35
  4. import json
  5. import zoneinfo
  6. from django_celery_beat.models import PeriodicTask, IntervalSchedule, ClockedSchedule, CrontabSchedule
  7. from Model.models import TimeZoneInfo
  8. from Service.CommonService import CommonService
  9. from django.core.exceptions import ObjectDoesNotExist
  10. class CeleryBeatObj:
  11. # celery beat对象,封装定时任务函数
  12. # https://github.com/celery/django-celery-beat
  13. @staticmethod
  14. def creat_interval_task(every, period, name, task, args=None, kwargs=None):
  15. """
  16. 创建间隔任务
  17. @param every: 时间间隔
  18. @param period: 单位,seconds,minutes,hours,days(或IntervalSchedule.SECONDS...)
  19. @param name: 任务名称
  20. @param task: 任务函数
  21. @param args: 参数
  22. @param kwargs: 参数
  23. @return:
  24. """
  25. if args is None:
  26. args = []
  27. args = json.dumps(args)
  28. if kwargs is None:
  29. kwargs = {}
  30. kwargs = json.dumps(kwargs)
  31. schedule, _ = IntervalSchedule.objects.get_or_create(every=every, period=period)
  32. PeriodicTask.objects.create(interval=schedule, name=name, task=task, args=args, kwargs=kwargs)
  33. @staticmethod
  34. def creat_clocked_task(name, task, time_stamp=0, timezone_offset=0, time_string='', args=None, kwargs=None):
  35. """
  36. 创建定时任务
  37. @param name: 任务名称
  38. @param task: 任务函数
  39. @param time_stamp: 时间戳
  40. @param timezone_offset: 时区偏移量
  41. @param time_string: 时间字符串
  42. @param args: 参数
  43. @param kwargs: 参数
  44. @return:
  45. """
  46. if args is None:
  47. args = []
  48. args = json.dumps(args)
  49. if kwargs is None:
  50. kwargs = {}
  51. kwargs = json.dumps(kwargs)
  52. # 不传时间戳时,将时间字符串转为时间戳
  53. if time_stamp == 0:
  54. time_stamp = CommonService.convert_to_timestamp(timezone_offset, time_string)
  55. # 时间戳转为东八区的时间字符串
  56. clocked_time = CommonService.get_date_from_timestamp(time_stamp, 8)
  57. schedule, _ = ClockedSchedule.objects.get_or_create(clocked_time=clocked_time)
  58. PeriodicTask.objects.create(clocked=schedule, one_off=True, name=name, task=task, args=args, kwargs=kwargs)
  59. @staticmethod
  60. def creat_crontab_task(
  61. timezone_offset, name, task,
  62. minute='*', hour='*', day_of_week='*', day_of_month='*', month_of_year='*', args=None, kwargs=None):
  63. """
  64. 创建周期任务
  65. @param timezone_offset: 时区偏移量
  66. @param name: 任务名称
  67. @param task: 任务函数
  68. @param minute: 分
  69. @param hour: 时
  70. @param day_of_week: 周,0-6对应周日到周六,也可写sun,mon,tue,wed,thu,fri,sat
  71. @param day_of_month: 月
  72. @param month_of_year: 年
  73. @param args: 参数
  74. @param kwargs: 参数
  75. @return:
  76. """
  77. if args is None:
  78. args = []
  79. args = json.dumps(args)
  80. if kwargs is None:
  81. kwargs = {}
  82. kwargs = json.dumps(kwargs)
  83. time_zone_info_qs = TimeZoneInfo.objects.filter(tz=timezone_offset).values('zone_info')
  84. if time_zone_info_qs.exists():
  85. zone_info = time_zone_info_qs[0]['zone_info']
  86. timezone = zoneinfo.ZoneInfo(zone_info)
  87. schedule, _ = CrontabSchedule.objects.get_or_create(
  88. minute=minute,
  89. hour=hour,
  90. day_of_week=day_of_week,
  91. day_of_month=day_of_month,
  92. month_of_year=month_of_year,
  93. timezone=timezone)
  94. PeriodicTask.objects.create(crontab=schedule, name=name, task=task, args=args, kwargs=kwargs)
  95. @staticmethod
  96. def disable_task(name):
  97. """
  98. 暂停任务
  99. @param name: 任务名称
  100. @return:
  101. """
  102. try:
  103. periodic_task = PeriodicTask.objects.get(name=name)
  104. periodic_task.enabled = False
  105. periodic_task.save()
  106. except ObjectDoesNotExist:
  107. pass
  108. @staticmethod
  109. def enable_task(name):
  110. """
  111. 恢复任务
  112. @param name: 任务名称
  113. @return:
  114. """
  115. try:
  116. periodic_task = PeriodicTask.objects.get(name=name)
  117. periodic_task.enabled = True
  118. periodic_task.save()
  119. except ObjectDoesNotExist:
  120. pass
  121. @staticmethod
  122. def del_task(name):
  123. """
  124. 删除任务
  125. @param name: 任务名称
  126. @return:
  127. """
  128. IntervalSchedule.objects.filter(periodictask__name=name).delete()
  129. CrontabSchedule.objects.filter(periodictask__name=name).delete()
  130. ClockedSchedule.objects.filter(periodictask__name=name).delete()
  131. PeriodicTask.objects.filter(name=name).delete()
  132. @staticmethod
  133. def update_task(name, **kwargs):
  134. """
  135. 更新任务
  136. @param name: 任务名称
  137. @param kwargs: 需要更新的属性及对应的值(可选)
  138. - interval: (every, period) 或 IntervalSchedule 对象,用于更新间隔任务
  139. - clocked_time: str 或 datetime,用于更新定时任务的时间戳
  140. - crontab: (minute, hour, day_of_week, day_of_month, month_of_year, timezone) 或 CrontabSchedule 对象,用于更新周期任务
  141. - task: 新的任务函数名
  142. - args: 新的参数列表
  143. - kwargs: 新的关键字参数字典
  144. - enabled: 是否启用任务(True 或 False)
  145. @return:
  146. None
  147. """
  148. periodic_task = PeriodicTask.objects.get(name=name)
  149. # 更新通用属性
  150. if 'task' in kwargs:
  151. periodic_task.task = kwargs['task']
  152. if 'args' in kwargs:
  153. periodic_task.args = json.dumps(kwargs['args'])
  154. if 'kwargs' in kwargs:
  155. periodic_task.kwargs = json.dumps(kwargs['kwargs'])
  156. if 'enabled' in kwargs:
  157. periodic_task.enabled = kwargs['enabled']
  158. # 更新不同类型任务的特定属性
  159. if 'interval' in kwargs:
  160. if isinstance(kwargs['interval'], tuple):
  161. every, period = kwargs['interval']
  162. schedule, _ = IntervalSchedule.objects.get_or_create(every=every, period=period)
  163. else:
  164. schedule = kwargs['interval']
  165. periodic_task.interval = schedule
  166. if 'clocked_time' in kwargs:
  167. if isinstance(kwargs['clocked_time'], str):
  168. clocked_time = CommonService.get_date_from_timestamp(
  169. CommonService.convert_to_timestamp(0, kwargs['clocked_time']), 8)
  170. else:
  171. clocked_time = kwargs['clocked_time']
  172. schedule, _ = ClockedSchedule.objects.get_or_create(clocked_time=clocked_time)
  173. periodic_task.clocked = schedule
  174. if 'crontab' in kwargs:
  175. if isinstance(kwargs['crontab'], tuple):
  176. minute, hour, day_of_week, day_of_month, month_of_year, timezone = kwargs['crontab']
  177. schedule, _ = CrontabSchedule.objects.get_or_create(
  178. minute=minute,
  179. hour=hour,
  180. day_of_week=day_of_week,
  181. day_of_month=day_of_month,
  182. month_of_year=month_of_year,
  183. timezone=timezone
  184. )
  185. else:
  186. schedule = kwargs['crontab']
  187. periodic_task.crontab = schedule
  188. periodic_task.save()