def create(self, validated_data): instance = super(Audit_JobSerializer, self).create(validated_data) datetime = validated_data['plan_time'] is_static_job = validated_data.get('is_static_job', False) schedule = CrontabSchedule.objects.filter((Q(minute=datetime.minute)) & (Q(hour=datetime.hour)) & (Q(day_of_month=datetime.day)) & (Q(month_of_year=datetime.month))) if not schedule: schedule = CrontabSchedule(minute=datetime.minute, hour=datetime.hour, day_of_month=datetime.day, month_of_year=datetime.month) schedule.save() else: schedule = schedule[0] task = PeriodicTask(crontab=schedule, name=str(uuid.uuid4()), task=ANALYSIS_FUNCTION, args=json.dumps([str(instance.id)]), description='audit_job') task.save() instance.task = task instance.save() return instance
def task_schedule_save(request): try: data = json.loads(request.body) _id = data.get('id') name = data.get('name') crontab = data.get('crontab') task_type = data.get('task_type') task_name = data.get('task_name') # 处理crontab表格式 if len(crontab.strip().split()) != 5: return HttpResponse(json.dumps({ 'code': 1, 'msg': 'crontab格式错误' }), content_type="application/json") else: minute, hour, day_of_week, day_of_month, month_of_year = crontab.strip( ).split() orm_crontab = CrontabSchedule.objects.filter( Q(minute=minute) & Q(hour=hour) & Q(day_of_week=day_of_week) & Q(day_of_month=day_of_month) & Q(month_of_year=month_of_year)) if orm_crontab: crontab_id = orm_crontab[0].id else: orm_crontab = CrontabSchedule(minute=minute, hour=hour, day_of_week=day_of_week, day_of_month=day_of_month, month_of_year=month_of_year, timezone=TIME_ZONE) orm_crontab.save() crontab_id = orm_crontab.id # 处理任务表格式 if task_type == '单任务': task = 'task_schedule.tasks.run_task' elif task_type == '任务组': task = 'task_schedule.tasks.run_tasks' args = f'["{task_name}"]' # 添加和编辑 if not _id: orm = PeriodicTask(name=name, task=task, args=args, crontab_id=crontab_id) else: orm = PeriodicTask.objects.get(id=_id) orm.name = name orm.task = task orm.args = args orm.crontab_id = crontab_id orm.save() return HttpResponse(json.dumps({ 'code': 0, 'msg': '操作成功' }), content_type="application/json") except Exception as e: return HttpResponse(json.dumps({ 'code': 1, 'msg': e }), content_type="application/json")