CeleryBeatObject.py 7.1 KB

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