Пример #1
0
 def save(self, *args, **kwargs):
     if self.calendario:
         self.fecha_calendario = "%s %s" % (self.calendario.inicio.strftime(
             '%Y-%m-%d %H:%M:%S'), self.calendario.fin.strftime('%H:%M:%S'))
     # end if
     if self.confirmacion == 2:
         self.cancelar = True
         self.calendario = None
         self.estado = 2
         self.fecha_canelacion = datetime.date.today()
     super(CitaMedica, self).save(*args, **kwargs)
     obj = PeriodicTask.objects.filter(
         name="Prueba crontab %d" % (self.pk),
         task="notificacion",
     )
     print "#######", self.pk, obj
     if not obj:
         crontab = CrontabSchedule(minute=1)
         crontab.save()
         obj = PeriodicTask.objects.create(name="Prueba crontab %d" %
                                           (self.pk),
                                           task="notificacion",
                                           crontab=crontab,
                                           args=[self.pk])
     else:
         obj.args = [self.pk]
         obj.save()
     print obj
Пример #2
0
    def post(self, request):
        ret = {"result": 0}

        if not request.user.has_perm(self.permission_required):
            ret["result"] = 1
            ret["msg"] = "Sorry,你没有'添加 CrontabSchedule '的权限,请联系运维!"
            return JsonResponse(ret)

        crontab_schedule_add_form = CrontabScheduleForm(request.POST)
        if not crontab_schedule_add_form.is_valid():
            ret["result"] = 1
            error_msg = json.loads(
                crontab_schedule_add_form.errors.as_json(escape_html=False))
            ret["msg"] = '\n'.join(
                [i["message"] for v in error_msg.values() for i in v])
            return JsonResponse(ret)

        try:
            cs_obj = CrontabSchedule(**crontab_schedule_add_form.cleaned_data)
            cs_obj.save()
        except Exception as e:
            ret["result"] = 1
            ret["msg"] = "CrontabSchedule 保存对象失败,请查看日志..."
            wslog_error().error("CrontabSchedule 保存对象失败, 错误信息: %s" % (e.args))
        else:
            ret["msg"] = "添加 CrontabSchedule 对象成功"
        return JsonResponse(ret)
Пример #3
0
def edit_peroid_task_by_id(task_id,
                           minute='*',
                           hour='*',
                           day_of_week='*',
                           day_of_month='*',
                           month_of_year='*',
                           args="[]",
                           kwargs="{}"):
    """
    @summary: 更新一个周期任务
    @param name: 用户定义的任务名称, 具有唯一性
    """
    try:
        period_task = PeriodicTask.objects.get(id=task_id)
    except PeriodicTask.DoesNotExist:
        return False, 'PeriodicTask.DoesNotExist'
    cron_param = {
        'minute': minute,
        'hour': hour,
        'day_of_week': day_of_week,
        'day_of_month': day_of_month,
        'month_of_year': month_of_year
    }
    try:
        cron_schedule = CrontabSchedule.objects.get(**cron_param)
    except CrontabSchedule.DoesNotExist:
        cron_schedule = CrontabSchedule(**cron_param)
        cron_schedule.save()
    period_task.crontab = cron_schedule
    period_task.args = args
    period_task.kwargs = kwargs
    period_task.save()
    return True, ''
Пример #4
0
 def test_CrontabSchedule_unicode(self):
     self.assertEqual(
         unicode(CrontabSchedule(minute=3, hour=3, day_of_week=None)),
         "3 3 * (m/h/d)")
     self.assertEqual(
         unicode(CrontabSchedule(minute=3, hour=3, day_of_week=None)),
         "3 3 * (m/h/d)")
def vacaciones(request):
    obj = Objeto.objects.all()
    id_obj_t = {}
    id_obj_f = {}
    for objeto in obj:
        logs_obj = Log.objects.filter(output = objeto)
        horas_par_t = []
        horas_par_f = []
        for i in range(len(logs_obj)):
            for j in range(len(logs_obj)):
                ta = True
                if logs_obj[i].hora.hour == logs_obj[j].hora.hour and logs_obj[i].status == logs_obj[j].status and j != i:
                    if logs_obj[i].status:
                        for t in horas_par_t:
                            if t.hora.hour == logs_obj[i].hora.hour:
                                ta = False
                        if ta:
                            horas_par_t.append(logs_obj[i])
                    else:
                        for f in horas_par_f:
                            if f.hora.hour == logs_obj[i].hora.hour:
                                ta = False
                        if ta:
                            horas_par_f.append(logs_obj[i])
        id_obj_t.update({objeto.id:horas_par_t})
        id_obj_f.update({objeto.id:horas_par_f})
    print id_obj_t
    print id_obj_f
    context = RequestContext(request)
    for i in id_obj_t:
        for j in range(len(id_obj_t[i])):
            vaca_cron = CrontabSchedule()
            vaca_cron.minute = id_obj_f[i][j].hora.minute
            vaca_cron.hour = id_obj_f[i][j].hora.hour
            vaca_cron.save()
            vaca_periodic = PeriodicTask()
            vaca_periodic.name = 'Vacaciones ' + str(id_obj_f[i][j].output.id)
            vaca_periodic.task = "module_1.tasks.on"
            vaca_periodic.crontab = vaca_cron
            vaca_periodic.args = "[ " +str(id_obj_f[i][j].output.pin)+ " ]"
            vaca_periodic.save()
    for i in id_obj_f:
        for j in range(len(id_obj_f[i])):
            vaca_cron = CrontabSchedule()
            vaca_cron.minute = id_obj_f[i][j].hora.minute
            vaca_cron.hour = id_obj_f[i][j].hora.hour
            vaca_cron.save()
            vaca_periodic = PeriodicTask()
            vaca_periodic.name = 'Vacaciones ' + str(id_obj_f[i][j].output.id)
            vaca_periodic.task = "module_1.tasks.off"
            vaca_periodic.crontab = vaca_cron
            vaca_periodic.args = "[ " +str(id_obj_f[i][j].output.pin)+ " ]"
            vaca_periodic.save()
    luces = Luz.objects.all()
    rule = Regla.objects.all()

    return render_to_response('luzauto.html',{'luz':luces, 'rules':rule},context)
Пример #6
0
 def schedule(task_name, minute, args=None, kwargs=None):
     results = CrontabSchedule.objects.filter(minute=minute)
     if results:
         c = results[0]
     else:
         c = CrontabSchedule()
         c.minute = minute
         c.save()
     return ProjectTask.schedule_with_crontab(task_name,c, args, kwargs)
Пример #7
0
def crontab_add(request):
    data = request.POST
    _instance = CrontabSchedule(minute=data.get('minute', '*'),
                                hour=data.get('hour', '*'),
                                day_of_week=data.get('day_of_week', '*'),
                                day_of_month=data.get('day_of_month', '*'),
                                month_of_year=data.get('month_of_year', '*'))
    _instance.save()
    return api.response()
Пример #8
0
def schedule_bill_plan(query, plan_id):
    if query['period'] == '1':
        months = '*'
    else:
        months = query['months']
    cronRecord = CrontabSchedule(minute=random.randint(0, 59), hour=random.randint(0, 20), day_of_month=int(query['generation_date']), month_of_year=months)
    cronRecord.save()
    periodicTask = PeriodicTask(name=query['name'], task=BILL_PLANS_TASK, crontab=cronRecord, kwargs=json.dumps({"plan_id": plan_id}), enabled=True)
    periodicTask.save()
    return None
Пример #9
0
def scheduleTest():
	crontab_obj = CrontabSchedule()
	crontab_obj.save()

	periodic_task = PeriodicTask(
		name='test',
		task="PbElite.tasks.testScheduler",
		crontab=crontab_obj
	)
	periodic_task.save()
Пример #10
0
def project_set(request):
    project = Project.objects.get(id=request.GET.get('id'))
    crontab = CrontabSchedule(minute=request.POST.get('minute'),
                              hour=request.POST.get('hour'))
    crontab.save()
    tname = project.name + "_task"
    try:
        ptask = PeriodicTask.objects.get(name=tname)
    except:
        print("ptask is null")
        ptask = None
    if ptask is not None:
        ptask.crontab = crontab
        ptask.enabled = request.POST.get('enable')
    else:
        ptask = PeriodicTask(name=project.name + "_task",
                             task='rango.script.task.executetest',
                             crontab=crontab,
                             args="[" + request.GET.get('id') + "]",
                             enabled=request.POST.get('enable'))
    ptask.save()
    address = request.POST.get("address")
    username = request.POST.get("username")
    password = request.POST.get("password")
    dbname = request.POST.get("dbname")
    port = request.POST.get("port")
    file = request.FILES.get('sql', None)
    sql = None
    if file is not None:
        sql = file
    else:
        sql = request.POST.get("sql")
        print(sql)
    try:
        dbconfigure = DbConfigure.objects.get(project=project)
    except:
        dbconfigure = None

    if dbconfigure is None:
        dbconfigure = DbConfigure(project=project,
                                  address=address,
                                  username=username,
                                  password=password,
                                  sql=sql,
                                  dbname=dbname,
                                  port=port)
    else:
        dbconfigure.address = address
        dbconfigure.username = username
        dbconfigure.password = password
        dbconfigure.sql = sql
        dbconfigure.dbname = dbname
        dbconfigure.port = port
    dbconfigure.save()
    return HttpResponseRedirect("/rango/project?id=" + request.GET.get('id'))
Пример #11
0
 def test_CrontabSchedule_unicode(self):
     self.assertEqual(unicode(CrontabSchedule(minute=3,
                                              hour=3,
                                              day_of_week=None)),
                      '3 3 * * * (m/h/d/dM/MY)')
     self.assertEqual(unicode(CrontabSchedule(minute=3,
                                              hour=3,
                                              day_of_week='tue',
                                              day_of_month='*/2',
                                              month_of_year='4,6')),
                      '3 3 tue */2 4,6 (m/h/d/dM/MY)')
Пример #12
0
 def test_CrontabSchedule_unicode(self):
     self.assertEqual(
         unicode(CrontabSchedule(minute=3, hour=3, day_of_week=None)),
         "3 3 * * * (m/h/d/dM/MY)")
     self.assertEqual(
         unicode(
             CrontabSchedule(minute=3,
                             hour=3,
                             day_of_week="tue",
                             day_of_month="*/2",
                             month_of_year="4,6")),
         "3 3 tue */2 4,6 (m/h/d/dM/MY)")
Пример #13
0
    def save(self, *args, **kwargs):
        """Create or update periodic task and cron schedule in DB"""
        # Save first, because the periodic_task needs this object's ID
        super(_ScheduleModel, self).save(*args, **kwargs)

        do_save = False
        pt = self.periodic_task

        if not pt:
            pt = self._new_periodic_task()

        if not pt.crontab:
            pt.crontab = self._save_crontab(CrontabSchedule())
            do_save = True
        elif self.schedule != self.crontab_to_schedule(pt.crontab):
            self._save_crontab(pt.crontab)
            do_save = True  # Need to update PeriodicTask, because it will signal the Scheduler to reload

        if self.active != pt.enabled:
            pt.enabled = self.active
            do_save = True

        if not pt.pk:
            pt.save()  # New periodic task object
            self.periodic_task = pt
            self.save(update_fields=('periodic_task', ))  # Update this object
        elif do_save:
            pt.save(update_fields=('enabled', 'crontab',
                                   'date_changed'))  # Update periodic task
Пример #14
0
def index(request):
    if request.method == 'POST':
        if 'schedule' in request.POST:
            
            # get the values from the form
            number = request.POST.get('phonenum')
            zipcode = request.POST.get('zipcode')
            sendtime = request.POST.get('sendtime')
            sendtime = sendtime.split(':')
            
            user = User.objects.filter(phoneNumber=number)
            if user:
                return render(request, 'home/signuperror.html')
            
            # add the job to the scheduler
            schedule = CrontabSchedule(hour=sendtime[0],minute=sendtime[1])
            schedule.save()
            arguments = json.dumps({"number":number,"zipcode":zipcode})
            modelData = dict(
                name=number,
                task="home.tasks.send",
                crontab_id=schedule.pk,
                kwargs=arguments,
            )
            periodicTask = PeriodicTask(**modelData)
            periodicTask.save()
            newUser = User(phoneNumber=number,zipCode=zipcode,sendTime=(sendtime[0] + sendtime[1]),cronjobID=schedule.pk)
            newUser.save()
            # try:
            #     periodicTask.save()
            # except:
            #     from django.db import connection
            #     print connection.queries
            #     raise
            return render(request, 'home/thanks.html')
            
        elif "remove" in request.POST:
            number = request.POST.get('phonenum')
            user = User.objects.filter(phoneNumber=number)
            if not user:
                return render(request, 'home/removeerror.html')
            CrontabSchedule.objects.get(pk=user[0].cronjobID).delete()
            user.delete()
            return render(request, 'home/goodbye.html')
            
        
    return render(request, 'home/index.html')
Пример #15
0
 def test_CrontabSchedule_schedule(self):
     s = CrontabSchedule(minute='3, 7', hour='3, 4', day_of_week='*',
                         day_of_month='1, 16', month_of_year='1, 7')
     self.assertEqual(s.schedule.minute, set([3, 7]))
     self.assertEqual(s.schedule.hour, set([3, 4]))
     self.assertEqual(s.schedule.day_of_week, set([0, 1, 2, 3, 4, 5, 6]))
     self.assertEqual(s.schedule.day_of_month, set([1, 16]))
     self.assertEqual(s.schedule.month_of_year, set([1, 7]))
Пример #16
0
def set_cron_schedule(task, minutes, hour, day_of_week):
    task.task = 'w3af_webui.tasks.scan_create_start'
    cron = CrontabSchedule.from_schedule(crontab(minute=minutes,
                                                 hour=hour,
                                                 day_of_week=day_of_week,
                                                 ))
    cron.save()
    task.crontab = cron
    task.interval = None
    task.save()
Пример #17
0
 def test_CrontabSchedule_schedule(self):
     s = CrontabSchedule(minute="3, 7",
                         hour="3, 4",
                         day_of_week="*",
                         day_of_month="1, 16",
                         month_of_year="1, 7")
     self.assertEqual(s.schedule.minute, set([3, 7]))
     self.assertEqual(s.schedule.hour, set([3, 4]))
     self.assertEqual(s.schedule.day_of_week, set([0, 1, 2, 3, 4, 5, 6]))
     self.assertEqual(s.schedule.day_of_month, set([1, 16]))
     self.assertEqual(s.schedule.month_of_year, set([1, 7]))
Пример #18
0
def add_peroid_task(task,
                    name=None,
                    minute='*',
                    hour='*',
                    day_of_week='*',
                    day_of_month='*',
                    month_of_year='*',
                    args="[]",
                    kwargs="{}"):
    """
    @summary: 添加一个周期任务
    @param task: 该task任务的模块路径名, 例如celery_sample.crontab_task
    @param name: 用户定义的任务名称, 具有唯一性 
    @note: PeriodicTask有很多参数可以设置,这里只提供简单常用的
    """
    cron_param = {
        'minute': minute,
        'hour': hour,
        'day_of_week': day_of_week,
        'day_of_month': day_of_month,
        'month_of_year': month_of_year
    }
    if not name:
        name = task
    try:
        cron_schedule = CrontabSchedule.objects.get(**cron_param)
    except CrontabSchedule.DoesNotExist:
        cron_schedule = CrontabSchedule(**cron_param)
        cron_schedule.save()
    try:
        PeriodicTask.objects.create(
            name=name,
            task=task,
            crontab=cron_schedule,
            args=args,
            kwargs=kwargs,
        )
    except Exception as e:
        return False, '%s' % e
    else:
        return True, ''
Пример #19
0
def set_cron_schedule(task, minutes, hour, day_of_week):
    task.task = 'w3af_webui.tasks.scan_create_start'
    cron = CrontabSchedule.from_schedule(
        crontab(
            minute=minutes,
            hour=hour,
            day_of_week=day_of_week,
        ))
    cron.save()
    task.crontab = cron
    task.interval = None
    task.save()
Пример #20
0
def make_periodic_crontab_task(name, task, minute, hour, day_of_week, *args, **kwargs):
    '''creates a new periodic crontab task, with name=name, updates fields if already exists'''
    pt, created = PeriodicTask.objects.get_or_create(name= name)
    
    if pt.interval:
        print("Warning, old task entry had an interval")
        if pt.interval.periodictask_set.count() == 1:
            print("Was the only one, deleting it")
            i = pt.interval
            i.delete()
            pt.interval = None
    
    if not pt.crontab:
        ct= CrontabSchedule()
    else:
        ct= pt.crontab
    
    ct.minute = minute
    ct.hour = hour
    ct.day_of_week = day_of_week
    ct.save()
    
    pt.crontab = ct
    pt.task = task
    pt.args = anyjson.serialize(args)
    pt.kwargs = anyjson.serialize(kwargs)
    pt.save()
    print ("saved task: %s, created: %s" % (str(pt), str(created)))
Пример #21
0
    def post_save(sender, instance, created, **kwargs):
        """
        Update djcelery beat schedule
        :param sender: The model class (Settings)
        :param instance: The actual instance being saved.
        :param created: A boolean; True if a new record was created
        :return:
        """

        # for migrations process
        if created:
            return

        from djcelery.models import PeriodicTask, CrontabSchedule

        try:
            task_object = PeriodicTask.objects.get(
                name=Settings.MAILING_TASK_LABEL)
            cron_object = task_object.crontab
        except ObjectDoesNotExist:
            cron_object = CrontabSchedule()
            task_object = PeriodicTask(name=Settings.MAILING_TASK_LABEL,
                                       task=Settings.MAILING_TASK_NAME)

        cron_object.minute = instance.mailing_time.minute
        cron_object.hour = instance.mailing_time.hour
        cron_object.save()

        task_object.crontab = cron_object
        task_object.args = "[{}]".format(instance.mailing_threads)
        task_object.save()
Пример #22
0
 def __call__(self, apps, schema_editor):
     from djcelery.models import PeriodicTask
     from djcelery.models import CrontabSchedule
     tab = CrontabSchedule.from_schedule(self.config.schedule)
     tab.save()
     PeriodicTask(
         enabled=not self.config.disabled,
         name=self.config.task_name,
         task=self.config.task,
         description=self.config.description,
         args=json.dumps([1, self.config.label]),  # Note 1 should always be the system user
         crontab=tab,
     ).save()
Пример #23
0
 def __call__(self, apps, schema_editor):
     from djcelery.models import PeriodicTask
     from djcelery.models import CrontabSchedule
     tab = CrontabSchedule.from_schedule(self.config.schedule)
     tab.save()
     PeriodicTask(
         enabled=not self.config.disabled,
         name=self.config.task_name,
         task=self.config.task,
         description=self.config.description,
         args=json.dumps([1, self.config.label
                          ]),  # Note 1 should always be the system user
         crontab=tab,
     ).save()
Пример #24
0
 def schedule_harvest_task(self, label, disabled):
     task_name = '{} harvester task'.format(label)
     tab = CrontabSchedule.from_schedule(crontab(minute=0, hour=0))
     tab.save()
     PeriodicTask.objects.update_or_create(
         name=task_name,
         defaults={
             'enabled': not disabled,
             'task': 'share.tasks.HarvesterTask',
             'description': 'Harvesting',
             'args': json.dumps([1, label]),  # Note 1 should always be the system user
             'crontab': tab,
         }
     )
Пример #25
0
def deactivate_task(uid, days=14):
    """
    uid:user.id
    days: 默认两周后关闭账户
    """
    from djcelery.models import CrontabSchedule, PeriodicTask
    from django.contrib.auth.models import User
    import datetime

    now = datetime.datetime.today()
    deadline = now + datetime.timedelta(minutes=3)
    task_date = CrontabSchedule()
    task_date.minute = deadline.timetuple().tm_min
    task_date.hour = deadline.timetuple().tm_hour
    task_date.day_of_month = deadline.timetuple().tm_mday
    task_date.month_of_year = deadline.timetuple().tm_mon
    try:
        from django.db import transaction
        with transaction.atomic():
            task_date.save()
    except:
        return False

    user = User.objects.get(pk=uid)

    name = "Deactivate_User_%s" % uid
    new_task = PeriodicTask(name=name)
    new_task.name = name
    new_task.task = 'templates.tasks.deactivate_tempuser'
    new_task.crontab = task_date
    new_task.args = "[%s]" % uid
    new_task.enabled = True
    try:
        from django.db import transaction
        with transaction.atomic():
            new_task.save()
    except:
        return False

    return True
Пример #26
0
 def schedule_cron(task_name, minute='*', hour='*', day_of_week='*', day_of_month='*', month_of_year='*' ,args=None, kwargs=None):
     # create the periodic task and the interval
     ptask_name = "%s_%s" % (task_name, datetime.now()) # create some name for the period task
     crontab_schedules = CrontabSchedule.objects.filter(minute=minute, hour=hour, day_of_week=day_of_week, day_of_month=day_of_month, month_of_year=month_of_year)
     if crontab_schedules: # just check if interval schedules exist like that already and reuse em
         crontab_schedule = crontab_schedules[0]
     else: # create a brand new interval schedule
         crontab_schedule = CrontabSchedule()
         crontab_schedule.minute = minute 
         crontab_schedule.hour = hour 
         crontab_schedule.day_of_week = day_of_week 
         crontab_schedule.day_of_month = day_of_month 
         crontab_schedule.month_of_year = month_of_year 
         crontab_schedule.save()
     
     ptask = PeriodicTask(name=ptask_name, task=task_name, crontab=crontab_schedule)
     if args:
         ptask.args = args
     if kwargs:
         ptask.kwargs = kwargs
     ptask.save()
     return TaskScheduler.objects.create(periodic_task=ptask)
Пример #27
0
def get_schedule(crontab):
    """Get djcelery CrontabSchedule object

    TODO: make real crontab validation
    """
    crontab_parts = crontab.split(" ")
    schedule_dict = {
        "minute": "*",
        "hour": "*",
        "day_of_week": "*",
        "day_of_month": "*",
        "month_of_year": "*",
    }
    if len(crontab_parts)==5:
        schedule_dict["minute"] = crontab_parts[0]
        schedule_dict["hour"] = crontab_parts[1]
        schedule_dict["day_of_week"] = crontab_parts[2]
        schedule_dict["day_of_month"] = crontab_parts[3]
        schedule_dict["month_of_year"] = crontab_parts[4]

    new_schedule = CrontabSchedule.from_schedule(schedules.crontab(**schedule_dict))
    new_schedule.save()
    return new_schedule
Пример #28
0
    def save(self, *args, **kwargs):
        if self.cron_schedule != self._original_cron_schedule and self.cron_schedule:
            minute, hour, day_of_week = self.cron_schedule.split()[:3]

            if not self.periodic_task:
                periodic_task = PeriodicTask(
                    task='humfrey.update.update',
                    kwargs=json.dumps({
                        'slug': self.slug,
                        'trigger': 'crontab'
                    }),
                    name='Update definition: {0}'.format(self.slug),
                    enabled=True)
                periodic_task.save()
                self.periodic_task = periodic_task

            crontab = self.periodic_task.crontab or CrontabSchedule()
            crontab.minute = minute
            crontab.hour = hour
            crontab.day_of_week = day_of_week
            crontab.save()

            self.periodic_task.crontab = crontab
            self.periodic_task.save()

            super(UpdateDefinition, self).save(*args, **kwargs)

        elif self.cron_schedule != self._original_cron_schedule and self.periodic_task:
            periodic_task, self.periodic_task = self.periodic_task, None

            super(UpdateDefinition, self).save(*args, **kwargs)

            periodic_task.crontab.delete()
            periodic_task.delete()
        else:
            super(UpdateDefinition, self).save(*args, **kwargs)
Пример #29
0
def createUserSchedule(schedule_id, desired_state):
	schedule = Schedule.objects.get(pk=schedule_id)
	circuit = schedule.circuit
	originalState = circuit.state
	start_date = schedule.start_time
	end_date = schedule.end_date

	# Schedule the start time (desired_state)
	start_crontab = CrontabSchedule(day_of_month=start_date.day, month_of_year=start_date.month,
		hour=start_date.hour, minute=start_date.minute)
	start_crontab.save()
	schedule.start_id = scheduleToggleTask(circuit.pk, desired_state, start_crontab)

	# Schedule the end time (original_state)
	end_crontab = CrontabSchedule(day_of_month=end_date.day, month_of_year=end_date.month,
		hour=end_date.hour, minute=end_date.minute)
	end_crontab.save()
	schedule.end_id = scheduleToggleTask(circuit.pk, originalState, end_crontab)

	#Save the id's to the Schedule table to delete later
	schedule.save()
Пример #30
0
def updateSchedule(schedule_id, start_date, end_date):
	schedule = Schedule.objects.get(pk=schedule_id)
	
	start_crontab = CrontabSchedule(day_of_month=start_date.day, month_of_year=start_date.month,
		hour=start_date.hour, minute=start_date.minute)
	end_crontab = CrontabSchedule(day_of_month=end_date.day, month_of_year=end_date.month,
		hour=end_date.hour, minute=end_date.minute)

	start_schedule = schedule.start_id
	end_schedule = schedule.end_id
	
	if start_schedule.crontab != start_crontab:
		start_crontab.save()
		start_schedule.crontab = start_crontab

	if end_schedule.crontab != end_crontab:
		end_crontab.save()
		end_schedule.crontab = end_crontab

	schedule.start_id = start_schedule
	schedule.end_id = end_schedule
	schedule.save()
Пример #31
0
def create_model_crontab(schedule, **kwargs):
    crontab = CrontabSchedule.from_schedule(schedule)
    crontab.save()
    return create_model(crontab=crontab, **kwargs)
Пример #32
0
def ExecuteFlow(req, app_uuid, tab, uuid):
    if tab not in ("plat", "group"):
        return Response({}, status=status.HTTP_404_NOT_FOUND)

    try:
        target_app = Apps.objects.get(pk=app_uuid)
    except:
        return Response({"success": False, "msg": _(u'应用不存在!')})
    data = ExecuteWorkFlowSerializer(data=req.data)
    if data.is_valid():
        if data.validated_data["kind"] == "zone":
            if not data.validated_data.get("region", None):
                return Response({"success": False, "msg": _(u"缺少区域ID!")})
            if data.validated_data["region"] != '__all__':
                if not cache.get(
                        utils.REDIS_REGION %
                    (req.user.uuid, app_uuid, data.validated_data["region"])):
                    return Response({"success": False, "msg": _(u"区域ID不存在!")})

            if tab == "plat":
                if not Zones.objects.safe_range(req.user,
                                                app_uuid,
                                                data.validated_data["uuids"],
                                                plat_uuid=uuid):
                    return Response({}, status=status.HTTP_403_FORBIDDEN)
            else:
                if not Zones.objects.safe_range(req.user,
                                                app_uuid,
                                                data.validated_data["uuids"],
                                                group_uuid=uuid):
                    return Response({}, status=status.HTTP_403_FORBIDDEN)
            target_map = ("Zones", data.validated_data["uuids"])
        else:
            target_map = ("Assets", data.validated_data["uuids"])
        if data.validated_data.get("cronExpression", None):
            crontab = CrontabSchedule.objects.filter(
                **data.validated_data["cronExpression"]).first()
            if not crontab:
                crontab = CrontabSchedule(
                    **data.validated_data["cronExpression"])
                crontab.save()
            periodic_task = PeriodicTask(
                name=data.validated_data["name"],
                task='exec_workflow',
                crontab=crontab,
                args=json.dumps([
                    req.user.account,
                    data.validated_data["workflow_uuid"],
                    target_map,
                ]),
                exchange='surge',
                routing_key='senders',
                kwargs=json.dumps({
                    "inject_env":
                    data.validated_data.get("inject_env", None),
                    "app_uuid":
                    app_uuid,
                    "first":
                    True,
                    "trigger":
                    2,
                    "tab":
                    tab,
                    "uuid":
                    uuid,
                    "region":
                    data.validated_data["region"],
                    "timeout":
                    data.validated_data.get("timeout", None)
                }))
            periodic_task.save()
            periodic_task_meta = PeriodicTaskMeta(periodictask=periodic_task,
                                                  userid=req.user.uuid,
                                                  user=req.user.name,
                                                  app_uuid=app_uuid,
                                                  appalias=target_app.appalias)
            periodic_task_meta.save()

            return Response({"success": True, "msg": _(u'定时成功!')})

        print data.validated_data
        celery.send_task('exec_workflow',
                         args=[
                             req.user.account,
                             data.validated_data["workflow_uuid"], target_map
                         ],
                         exchange='surge',
                         routing_key='senders',
                         kwargs={
                             "inject_env":
                             data.validated_data.get("inject_env", None),
                             "app_uuid":
                             app_uuid,
                             "first":
                             True,
                             "trigger":
                             1,
                             "tab":
                             tab,
                             "uuid":
                             uuid,
                             "region":
                             data.validated_data["region"],
                             "timeout":
                             data.validated_data.get("timeout", None)
                         })
    else:
        return Response({
            "success": False,
            "msg": data.errors
        },
                        status=status.HTTP_400_BAD_REQUEST)
    return Response({"success": True, "msg": _(u'指令发送成功,请等候!')})
def add_rule(request):
    context = RequestContext(request)
    id= request.POST.get('id')
    lista_permitidos = Usuario.objects.filter(permisos_luces=id)
    if lista_permitidos.__str__() != "[]":
        for permitido in lista_permitidos:
            if permitido.user.id == request.user.id:
                if request.method=='POST':
                    print "hola"
                    luz = Luz.objects.get(id = request.POST['id'])
                    dias = eval(request.POST['days'])
                    print "0"
                    print dias,"-",request.POST['days']
                    hora = eval(request.POST['hours'])
                    print "1"
                    regla = Regla()
                    print "2"
                    regla.relacion = luz
                    print "3"
                    regla.pin = luz.pin
                    print "4"
                    if request.POST['status'] == "false":
                        regla.status=False
                        print request.POST['status']
                    else:
                        regla.status=True
                        print "true"
                    print "4"
                    days_t = []
                    for i in dias:
                        if i=="Lunes":
                            print "Lun"
                            regla.lun = True
                            days_t.append(1)
                        elif i=="Martes":
                            print "Mar"
                            regla.mar = True
                            days_t.append(2)
                        elif i=="Miercoles":
                            print "Mie"
                            regla.mie = True
                            days_t.append(3)
                        elif i=="Jueves":
                            print "Jue"
                            regla.jue = True
                            days_t.append(4)
                        elif i=="Viernes":
                            print "Vie"
                            regla.vie = True
                            days_t.append(5)
                        elif i=="Sabado":
                            print "Sab"
                            regla.sab = True
                            days_t.append(6)
                        elif i=="Domingo":
                            print "Dom"
                            regla.dom = True
                            days_t.append(0)
                    regla.from_hour = hora[0]
                    f_h = str(hora[0])
                    print "from"
                    regla.to_hour = hora[1]
                    t_h = str(hora[1])
                    print "to"
                    regla.save()
                    print "save"
                    cron = CrontabSchedule()
                    cron.minute = f_h[-2:]
                    cron.hour = f_h[:2]
                    print days_t
                    aux=""
                    for i in range(len(days_t)):
                        if i == len(days_t)-1:
                            aux += str(days_t[i])
                        else:
                            aux += str(days_t[i])+","
                    days_t = aux
                    print days_t
                    cron.day_of_week = days_t
                    cron.save()
                    print "cron save"
                    regla = Regla.objects.latest('id')
                    cronT = CrontabSchedule.objects.latest('id')
                    print "regla y cronT"
                    periodic = PeriodicTask()
                    print "P_t"
                    na = str(regla.id)+"_1"
                    print "na"
                    periodic.name = na
                    print "name"
                    if regla.status:
                        periodic.task = "module_1.tasks.on"
                    else:
                        periodic.task = "module_1.tasks.off"
                    print "status"
                    periodic.crontab = cronT
                    print "cron= p_t"
                    periodic.args = "[ " +str(regla.pin)+ " ]"
                    print "arg"
                    periodic.save()
                    print "periodic save"
                    cron = CrontabSchedule()
                    cron.minute = t_h[-2:]
                    cron.hour = t_h[:2]
                    print days_t
                    aux=""
                    for i in range(len(days_t)):
                        if i == len(days_t)-1:
                            aux += str(days_t[i])
                        else:
                            aux += str(days_t[i])+","
                    days_t = aux
                    print days_t
                    cron.day_of_week = days_t
                    cron.save()
                    print "cron save"
                    cronT = CrontabSchedule.objects.latest('id')
                    print "regla y cronT"
                    periodic = PeriodicTask()
                    print "P_t"
                    na = str(regla.id)+"_2"
                    print "na"
                    periodic.name = na
                    print "name"
                    if regla.status:
                        periodic.task = "module_1.tasks.off"
                    else:
                        periodic.task = "module_1.tasks.on"
                    print "status"
                    periodic.crontab = cronT
                    print "cron= p_t"
                    periodic.args = "[ " +str(regla.pin)+ " ]"

                    print "arg"
                    periodic.save()
                    print "periodic save"

                    rule = Regla.objects.all()
                    return render_to_response('tab.html',{'rules':rule},context)
    rule = Regla.objects.all()
    response = render_to_response('tab.html',{'rules':rule},context)
    response.status_code = 202
    return response
Пример #34
0
def create_model_crontab(schedule, **kwargs):
    return create_model(crontab=CrontabSchedule.from_schedule(schedule),
                        **kwargs)
Пример #35
0
def create_model_crontab(schedule, **kwargs):
    return create_model(crontab=CrontabSchedule.from_schedule(schedule),
                        **kwargs)
Пример #36
0
    def save(self, *args, **kwargs):
        # Removes all other entries if there are any
        self.__class__.objects.exclude(id=self.id).delete()

        # creates new checkout task
        if self.checkout_task is None:
            cron = CrontabSchedule(
                minute=self.scheduled_verification_time.minute,
                hour=self.scheduled_verification_time.hour)
            cron.save()

            ctask = PeriodicTask(
                name="scheduled-checkout-%s" % cron.id,
                task="apps.organization.tasks.automatic_checkout",
                crontab=cron,
                queue="celery")
            ctask.save()
            self.checkout_task = ctask
        else:
            ctask = self.checkout_task
            cron = ctask.crontab
            cron.hour = self.scheduled_verification_time.hour
            cron.minute = self.scheduled_verification_time.minute
            cron.save()
            ctask.save()

        # creates new reminder task
        if self.reminder_task is None:
            cron = CrontabSchedule(minute=self.checkout_reminder_time.minute,
                                   hour=self.checkout_reminder_time.hour)
            cron.save()

            rtask = PeriodicTask(
                name="scheduled-reminder-%s" % cron.id,
                task="apps.organization.tasks.checkout_notification",
                crontab=cron,
                queue="celery")
            rtask.save()
            self.reminder_task = rtask
        else:
            rtask = self.reminder_task
            cron = rtask.crontab
            cron.hour = self.checkout_reminder_time.hour
            cron.minute = self.checkout_reminder_time.minute
            cron.save()
            rtask.save()

        super(OrgSettings, self).save(*args, **kwargs)