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)
	def schedule_every(self, task_name, period, every, crontab='',args=None, kwargs=None, queue=''):
		main_task = 'optimizer.tasks.base_task'
		permissible_periods = ['days', 'hours', 'minutes', 'seconds']

		# create the periodic task and the interval
		ptask_name = "%s_%s" % (task_name, datetime.datetime.now()) # create some name for the period task

		if period and every:
			if period not in permissible_periods:
				raise Exception('Invalid period specified')


			interval_schedules = IntervalSchedule.objects.filter(period=period, every=every)
			if interval_schedules: # just check if interval schedules exist like that already and reuse em
				interval_schedule = interval_schedules[0]
			else: # create a brand new interval schedule
				interval_schedule = IntervalSchedule()
				interval_schedule.every = every # should check to make sure this is a positive int
				interval_schedule.period = period
				interval_schedule.save()
			ptask = PeriodicTask(name=ptask_name, task=main_task, interval=interval_schedule)

		elif crontab:
			ptask = PeriodicTask(name=ptask_name, task=main_task, crontab=crontab)

		if args:
			ptask.args = args
		if kwargs:
			ptask.kwargs = kwargs
		ptask.queue = queue
		ptask.save()
		return ptask
예제 #3
0
 def schedule_every(task_name, period, every, args=None, kwargs=None):
     """ 
     schedules a task by name every "every" "period". So an example call would be:
     TaskScheduler('mycustomtask', 'seconds', 30, [1,2,3]) 
     that would schedule your custom task to run every 30 seconds with the arguments 1,2 and 3 passed to the actual task. 
     """
     permissible_periods = ["days", "hours", "minutes", "seconds"]
     if period not in permissible_periods:
         raise Exception("Invalid period specified")
     # create the periodic task and the interval
     ptask_name = "%s_%s" % (task_name, datetime.now())  # create some name for the period task
     interval_schedules = IntervalSchedule.objects.filter(period=period, every=every)
     if interval_schedules:  # just check if interval schedules exist like that already and reuse em
         interval_schedule = interval_schedules[0]
     else:  # create a brand new interval schedule
         interval_schedule = IntervalSchedule()
         interval_schedule.every = every  # should check to make sure this is a positive int
         interval_schedule.period = period
         interval_schedule.save()
     ptask = PeriodicTask(name=ptask_name, task=task_name, interval=interval_schedule)
     if args:
         ptask.args = args
     if kwargs:
         ptask.kwargs = kwargs
     ptask.save()
     return TaskScheduler.objects.create(periodic_task=ptask)
예제 #4
0
 def schedule_every(task_name, period, every, args=None, kwargs=None):
     """ 
     schedules a task by name every "every" "period". So an example call would be:
     TaskScheduler('mycustomtask', 'seconds', 30, [1,2,3]) 
     that would schedule your custom task to run every 30 seconds with the arguments 1,2 and 3 passed to the actual task. 
     """
     permissible_periods = ['days', 'hours', 'minutes', 'seconds']
     if period not in permissible_periods:
         raise Exception('Invalid period specified')
     # create the periodic task and the interval
     ptask_name = "%s_%s" % (task_name, datetime.now()
                             )  # create some name for the period task
     interval_schedules = IntervalSchedule.objects.filter(period=period,
                                                          every=every)
     if interval_schedules:  # just check if interval schedules exist like that already and reuse em
         interval_schedule = interval_schedules[0]
     else:  # create a brand new interval schedule
         interval_schedule = IntervalSchedule()
         interval_schedule.every = every  # should check to make sure this is a positive int
         interval_schedule.period = period
         interval_schedule.save()
     ptask = PeriodicTask(name=ptask_name,
                          task=task_name,
                          interval=interval_schedule)
     if args:
         ptask.args = args
     if kwargs:
         ptask.kwargs = kwargs
     ptask.save()
     return TaskScheduler.objects.create(periodic_task=ptask)
예제 #5
0
    def schedule_every(self, every, period, args=None, kwargs=None):
        print "Scheduling %s to run every %s %s" % (self.name, every, period)
        if self.periodic_task:
            self.periodic_task.delete()
        
        print "Cleared all current periodic tasks"

        permissible_periods = ['days', 'hours', 'minutes', 'seconds']
        if period not in permissible_periods:
            raise Exception('Invalid period specified: %s, must be one of: %s' % (period, ','.join(permissible_periods)))
        # create the periodic task and the interval
        ptask_name = "%s_%s" % (self.celery_task_name, self.name)
        interval_schedules = IntervalSchedule.objects.filter(period=period, every=every)
        if interval_schedules: # just check if interval schedules exist like that already and reuse em
            interval_schedule = interval_schedules[0]
        else:
            interval_schedule = IntervalSchedule()
            interval_schedule.every = every
            interval_schedule.period = period
            interval_schedule.save()
        
        print "Creating new periodic task"
        periodic_task = PeriodicTask(name=ptask_name, task=self.celery_task_name, interval=interval_schedule)
        if args:
            periodic_task.args = args
        if kwargs:
            periodic_task.kwargs = kwargs
        periodic_task.save()
        print "Attached the periodic task to the project task"
        self.periodic_task = periodic_task

        print "Saving project task"
        self.save()
예제 #6
0
파일: models.py 프로젝트: vladz/drafts
    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()
예제 #7
0
 def schedule_with_crontab(task_name, crontab_schedule, args=None, kwargs=None):
     ptask_name = "%s_%s" % (task_name, datetime.datetime.now())
     ptask = PeriodicTask(name=ptask_name,
                          task=task.name,
                          crontab=crontab_schedule
                          )
     if args:
         ptask.args = args
     if kwargs:
         ptask.kwargs = kwargs
     ptask.save()
     return ProjectTask.objects.create(periodic_task=ptask)
예제 #8
0
 def schedule_every(task_name, task, period, every, args=None, kwargs=None):
     permissible_periods = ['days', 'hours', 'minutes', 'seconds']
     if period not in permissible_periods:
         raise Exception('Invalid period specified')
     # create the periodic task and the interval
     interval_schedules = IntervalSchedule.objects.filter(period=period, every=every)
     if interval_schedules: # just check if interval schedules exist like that already and reuse em
         interval_schedule = interval_schedules[0]
     else: # create a brand new interval schedule
         interval_schedule = IntervalSchedule()
         interval_schedule.every = every # should check to make sure this is a positive int
         interval_schedule.period = period 
         interval_schedule.save()
     ptask = PeriodicTask(name=task_name, task=task, interval=interval_schedule)
     if args:
         ptask.args = args
     if kwargs:
         ptask.kwargs = kwargs
     ptask.save()
     return TaskScheduler.objects.create(periodic_task=ptask)
예제 #9
0
 def schedule_task_every(task_name, every, period, args=None, kwargs=None):
     permissible_periods = ['days', 'hours', 'minutes', 'seconds']
     if period not in permissible_periods:
         raise Exception('Invalid period specified')
     # create the periodic task and the interval
     ptask_name = "%s_%s" % (task_name, datetime.datetime.now())
     interval_schedules = IntervalSchedule.objects.filter(period=period, every=every)
     if interval_schedules: # just check if interval schedules exist like that already and reuse em
         interval_schedule = interval_schedules[0]
     else:
         interval_schedule = IntervalSchedule()
         interval_schedule.every = every
         interval_schedule.period = period
         interval_schedule.save()
     ptask = PeriodicTask(name=ptask_name, task=task_name, interval=interval_schedule)
     if args:
         ptask.args = args
     if kwargs:
         ptask.kwargs = kwargs
     ptask.save()
     return ProjectTask.objects.create(periodic_task=ptask, name=task_name)
예제 #10
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
예제 #11
0
파일: models.py 프로젝트: komaliitm/Patedu
 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)
예제 #12
0
 def schedule_every(task_name, task, period, every, args=None, kwargs=None):
     permissible_periods = ['days', 'hours', 'minutes', 'seconds']
     if period not in permissible_periods:
         raise Exception('Invalid period specified')
     # create the periodic task and the interval
     interval_schedules = IntervalSchedule.objects.filter(period=period,
                                                          every=every)
     if interval_schedules:  # just check if interval schedules exist like that already and reuse em
         interval_schedule = interval_schedules[0]
     else:  # create a brand new interval schedule
         interval_schedule = IntervalSchedule()
         interval_schedule.every = every  # should check to make sure this is a positive int
         interval_schedule.period = period
         interval_schedule.save()
     ptask = PeriodicTask(name=task_name,
                          task=task,
                          interval=interval_schedule)
     if args:
         ptask.args = args
     if kwargs:
         ptask.kwargs = kwargs
     ptask.save()
     return TaskScheduler.objects.create(periodic_task=ptask)
예제 #13
0
def create_periodic_task(task_name, period, every, args=None, kwargs=None):
    """ adapted from
        https://groups.google.com/forum/#!msg/celery-users/CZXCh8sCK5Q/ihZgMV2HWWYJ
        c/o Jean Mark

        Schedules a task by name every "every" "period".
        So an example call would be:
            create_periodic_task('mycustomtask', 'seconds', 30, [1,2,3])
        that would schedule your custom task to run every 30 seconds
        with the arguments 1,2 and 3 passed to the actual task.
    """
    # create the schedule
    interval_schedule = manage_interval(period, every)
    # create the periodic task
    ptask_name = "%s_%s" % (task_name, timezone.now())
    ptask = PeriodicTask(name=ptask_name,
                         task=task_name,
                         interval=interval_schedule)
    if args:
        ptask.args = args
    if kwargs:
        ptask.kwargs = kwargs
    ptask.save()
    return ptask
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