コード例 #1
0
 def test_flush_queue_without_jobs_limit_limit_at_300_by_default(self):
     """Make sure that the number of job run by default is 300.
     """
     for _ in xrange(305):
         schedule(_dummy)
     management.call_command('flush_queue')
     self.assertEqual(Job.objects.filter(executed=None).count(), 5)
コード例 #2
0
ファイル: test_commands.py プロジェクト: DjNero/django-async
 def test_flush_queue_without_jobs_limit_limit_at_300_by_default(self):
     """Make sure that the number of job run by default is 300.
     """
     for _ in xrange(305):
         schedule(_dummy)
     management.call_command('flush_queue')
     self.assertEqual(Job.objects.filter(executed=None).count(), 5)
コード例 #3
0
ファイル: test_commands.py プロジェクト: DjNero/django-async
 def test_flush_queue_with_jobs_limit(self):
     """Make sure that the number of job run is the same
     as the input jobs limit.
     """
     for _ in xrange(5):
         schedule(_dummy)
     management.call_command('flush_queue', jobs=2)
     self.assertEqual(Job.objects.filter(executed=None).count(), 3)
コード例 #4
0
ファイル: test_commands.py プロジェクト: DjNero/django-async
 def test_asap_tasks(self):
     """Make sure that tasks scheduled for immediate execution
     are run.
     """
     schedule(_dummy)
     self.assertEqual(Job.objects.filter(executed=None).count(), 1)
     management.call_command('flush_queue')
     self.assertEqual(Job.objects.filter(executed=None).count(), 0)
コード例 #5
0
 def test_asap_tasks(self):
     """Make sure that tasks scheduled for immediate execution
     are run.
     """
     schedule(_dummy)
     self.assertEqual(Job.objects.filter(executed=None).count(), 1)
     management.call_command('flush_queue')
     self.assertEqual(Job.objects.filter(executed=None).count(), 0)
コード例 #6
0
 def test_flush_queue_with_jobs_limit(self):
     """Make sure that the number of job run is the same
     as the input jobs limit.
     """
     for _ in xrange(5):
         schedule(_dummy)
     management.call_command('flush_queue', jobs=2)
     self.assertEqual(Job.objects.filter(executed=None).count(), 3)
コード例 #7
0
 def test_scheduled_runs_first_when_added_last(self):
     """Make sure that the scheduled job is always run first.
     """
     global ORDER
     ORDER = []
     schedule(_dummy, args=[2])
     schedule(_dummy, args=[1], run_after=datetime.now())
     management.call_command('flush_queue')
     self.assertEqual(ORDER, [1, 2])
コード例 #8
0
ファイル: test_commands.py プロジェクト: DjNero/django-async
 def test_scheduled_runs_first_when_added_last(self):
     """Make sure that the scheduled job is always run first.
     """
     global ORDER
     ORDER = []
     schedule(_dummy, args=[2])
     schedule(_dummy, args=[1], run_after=datetime.now())
     management.call_command('flush_queue')
     self.assertEqual(ORDER, [1, 2])
コード例 #9
0
 def test_scheduled_runs_last_when_has_higher_priority(self):
     """The lowest priority scheduled job runs before the highest
     priority non-scheduled job.
     """
     global ORDER
     ORDER = []
     schedule(_dummy, args=[1], priority=5)
     schedule(_dummy, args=[2], priority=1, run_after=datetime.now())
     management.call_command('flush_queue')
     self.assertEqual(ORDER, [1, 2])
コード例 #10
0
ファイル: test_commands.py プロジェクト: DjNero/django-async
 def test_scheduled_runs_last_when_has_higher_priority(self):
     """The lowest priority scheduled job runs before the highest
     priority non-scheduled job.
     """
     global ORDER
     ORDER = []
     schedule(_dummy, args=[1], priority=5)
     schedule(_dummy, args=[2], priority=1, run_after=datetime.now())
     management.call_command('flush_queue')
     self.assertEqual(ORDER, [1, 2])
コード例 #11
0
 def test_queue_fails_on_error(self):
     """Make sure that the queue flushing stops on the first error.
     """
     schedule(_dummy, "Error")
     schedule(_dummy)
     self.assertEqual(Job.objects.filter(executed=None).count(), 2)
     with self.assertRaises(Exception):
         management.call_command('flush_queue')
     self.assertEqual(Job.objects.filter(executed=None).count(), 2)
     management.call_command('flush_queue')
     self.assertEqual(Job.objects.filter(executed=None).count(), 1)
コード例 #12
0
ファイル: test_commands.py プロジェクト: DjNero/django-async
 def test_queue_fails_on_error(self):
     """Make sure that the queue flushing stops on the first error.
     """
     schedule(_dummy, kwargs={'error': "Error"})
     schedule(_dummy)
     self.assertEqual(Job.objects.filter(executed=None).count(), 2)
     with self.assertRaises(Exception):
         management.call_command('flush_queue')
     self.assertEqual(Job.objects.filter(executed=None).count(), 2)
     management.call_command('flush_queue')
     self.assertEqual(Job.objects.filter(executed=None).count(), 1)
コード例 #13
0
def setpoints(timestamp):

    from schedule import schedule

    hourstart = int(float(timestamp[11:13]) + float(timestamp[14:16]) / 60)

    mbed_tlow = schedule('MBED', hourstart)
    lbed_tlow = schedule('LBED', hourstart)
    obed_tlow = schedule('OBED', hourstart)

    setdict = {'MBED': mbed_tlow, 'LBED': lbed_tlow, 'OBED': obed_tlow}

    return setdict
コード例 #14
0
 def test_unicode_with_args(self):
     """Make sure unicode handling deals with args properly.
     """
     self.assertEqual(unicode(schedule(
             'async.tests.test_models._fn', args=['argument'])),
         "async.tests.test_models._fn('argument')")
     self.assertEqual(unicode(schedule(
             'async.tests.test_models._fn', args=['a1', 'a2'])),
         "async.tests.test_models._fn('a1', 'a2')")
     self.assertEqual(unicode(schedule(
             'async.tests.test_models._fn', args=[1, 2])),
         'async.tests.test_models._fn(1, 2)')
     self.assertEqual(unicode(schedule(
             'async.tests.test_models._fn', args=[dict(k='v', x=None)])),
         "async.tests.test_models._fn({'x': None, 'k': 'v'})")
コード例 #15
0
ファイル: test_models.py プロジェクト: MechanisM/django-async
 def test_unicode_with_args_and_kwargs(self):
     """Make sure unicode handling deals with kwargs properly.
     """
     self.assertEqual(unicode(schedule(
             'async.tests.test_models._fn',
                 args=['argument'], kwargs=dict(k='v', x=None))),
         "async.tests.test_models._fn('argument', x=None, k='v')")
コード例 #16
0
ファイル: test_schedule.py プロジェクト: KayEss/django-async
 def test_schedule_by_function(self):
     """We must be able to schedule a job by giving a function.
     """
     job = schedule(_example)
     # Different versions of Django will import this file differently
     self.assertTrue(job.name.endswith(
         'async.tests.test_schedule._example'))
コード例 #17
0
 def test_schedule_by_function(self):
     """We must be able to schedule a job by giving a function.
     """
     job = schedule(_example)
     # Different versions of Django will import this file differently
     self.assertTrue(
         job.name.endswith('async.tests.test_schedule._example'))
コード例 #18
0
ファイル: test_models.py プロジェクト: iamklang/django-async
 def test_identity(self):
     """Make sure that the identity we get is the same as in another
     test when given the same arguments.
     """
     job = schedule('async.tests.test_models._fn')
     self.assertEqual(job.identity,
         '289dbff9c1bd746fc444a20d396986857a6e8f04')
コード例 #19
0
 def test_identity(self):
     """Make sure that the identity we get is the same as in another
     test when given the same arguments.
     """
     job = schedule('async.tests.test_models._fn')
     self.assertEqual(job.identity,
                      '289dbff9c1bd746fc444a20d396986857a6e8f04')
コード例 #20
0
ファイル: test_models.py プロジェクト: iamklang/django-async
 def test_unicode(self):
     """Make sure the that the Unicode form of the Error works.
     """
     job = schedule('async.tests.test_models._fn')
     error = Error.objects.create(job=job, exception="Exception text")
     self.assertTrue(
         unicode(error).endswith(u' : Exception text'), unicode(error))
コード例 #21
0
 def test_unicode(self):
     """Make sure the that the Unicode form of the Error works.
     """
     job = schedule('async.tests.test_models._fn')
     error = Error.objects.create(job=job, exception="Exception text")
     self.assertTrue(
         unicode(error).endswith(u' : Exception text'), unicode(error))
コード例 #22
0
def start_gen():
    _data_car, _data_road, _data_cross, G_cross=graph_create.data_gen()
    _list_rest=[]    #没走的车集合_list_rest,元素类型Car
    for value in _data_car.values():
        _list_rest.append(value)
    #_road2d:每个road一个状态,长度为length的int数组
    #初始化_road2d的状态
    #_road2d=[[]]*len(_data_road)  #_road2d存储每条路当前的状态   key: roadid value:list 下标
    _act_road={}           #_act_road存储每条路id对应_road的下标,这个可以考虑一下是不是不用存,但是主要考虑时间复杂度?
    _act_car={}             #_act_car存储每辆车对应road和位置
    for road in _data_road.items():
        _act_road[road[0]]=[0]*road[1].length
    for car in _data_car.items():          #_dict_car存储每辆车当前的状态   key:carid  value:二元组(当前道路,当前位置)
        _act_car[car[0]]=(car[1].src,-2)           #  -2表示未发车,-1表示在起始位置后一个(可以发车) 大等于0表示在路上的位置
    Time_now=1
    while 1:
        #路上调度
        _act_car,_act_road=schedule(Time_now,_act_car,_act_road)          #wy接口
        #发车部分
        if len(_list_rest)>0:
            #还有待发的车
            if len(_list_rest)<5:
                for rests in _list_rest:
                    _act_car[rests.id][1]=-1  #预备发车
                _list_rest.clear()
            else:
                for rests in _list_rest:
                    if car.start<=Time_now:
                        go_or_not = random.randint(1, 1 / (1 - start_rate))  # 摇色子决定走不走
                        if go_or_not > 1:  # 摇到1不走
                            i = 0
コード例 #23
0
 def test_unicode_generated(self):
     """Make sure that the unicode generated by a real scheduled job
     and one used to create an identity match.
     """
     job1 = schedule('async.tests.test_deschedule._example')
     job2 = Job(name='async.tests.test_deschedule._example',
         args="[]", kwargs="{}")
     self.assertEqual(job1.identity, sha1(unicode(job2)).hexdigest())
コード例 #24
0
 def test_unicode_with_kwargs(self):
     """Make sure unicode handling deals with kwargs properly.
     """
     self.assertEqual(
         unicode(
             schedule('async.tests.test_models._fn',
                      kwargs=dict(k='v', x=None))),
         "async.tests.test_models._fn(x=None, k='v')")
コード例 #25
0
 def test_deschedule_by_name(self):
     """We must be able to deschedule a job by giving its name.
     """
     job = schedule('async.tests.test_deschedule._example')
     self.assertEqual(job.name, 'async.tests.test_deschedule._example')
     deschedule('async.tests.test_deschedule._example')
     job = Job.objects.get(pk=job.pk)
     self.assertIsNotNone(job.cancelled)
コード例 #26
0
 def test_model_creation(self):
     """Make sure schedule API works.
     """
     job = schedule('async.tests.test_models._fn')
     self.assertEqual(Job.objects.all().count(), 1)
     self.assertEqual(unicode(job), "async.tests.test_models._fn()")
     self.assertEqual(job.identity,
         '289dbff9c1bd746fc444a20d396986857a6e8f04')
コード例 #27
0
def log_async(report, fmt, conf={}):
    #now = str(datetime.datetime.utcnow().replace(tzinfo=utc))
    now = random.randint(1, 1000000000)
    now = "{0:0>9}".format(now)
    fn = 'api_reports_get_data_' + report + '_' + str(now) + '.' + fmt + '.gz'

    url = '<a href="http://10.1.4.56:8000/api/cache/' + report + '/' + fn + '">Download</a>'

    schedule(
        'aswrap.async_wrappers.api_reports_get_data',
        args=(
            report,
            fmt,
            fn,
            conf)
        )
    return url
コード例 #28
0
 def test_unicode_with_args_and_kwargs(self):
     """Make sure unicode handling deals with kwargs properly.
     """
     job = schedule('async.tests.test_models._fn',
         args=['argument'], kwargs=dict(k='v', x=None))
     self.assertEqual(unicode(job),
         "async.tests.test_models._fn('argument', x=None, k='v')")
     self.assertEqual(job.identity,
         '2ce2bb7935439a6ab3f111882f359a06b36bf995')
コード例 #29
0
 def test_unicode_with_kwargs(self):
     """Make sure unicode handling deals with kwargs properly.
     """
     job = schedule('async.tests.test_models._fn',
         kwargs=dict(k='v', x=None))
     self.assertEqual(unicode(job),
         "async.tests.test_models._fn(x=None, k='v')")
     self.assertEqual(job.identity,
         '60941ebcc096c0223ba1db02b3d256f19ba553a3')
コード例 #30
0
 def test_flush_queue_with_cancelled_jobs__should_not_be_executed(self):
     """Make sure that the number of job run by default is 300.
     """
     for _ in xrange(5):
         job = schedule(_dummy)
         deschedule(job.name)
     management.call_command('flush_queue')
     self.assertEqual(Job.objects.filter(executed=None).count(), 5)
     self.assertEqual(Job.objects.filter(cancelled=None).count(), 0)
コード例 #31
0
 def test_flush_queue_with_cancelled_jobs__should_not_be_executed(self):
     """Make sure that the number of job run by default is 300.
     """
     for _ in xrange(5):
         job = schedule(_dummy)
         deschedule(job.name)
     management.call_command('flush_queue')
     self.assertEqual(Job.objects.filter(executed=None).count(), 5)
     self.assertEqual(Job.objects.filter(cancelled=None).count(), 0)
コード例 #32
0
 def test_deschedule_by_function(self):
     """We must be able to schedule a job by giving a function.
     """
     job = schedule(_example)
     # Different versions of Django will import this file differently
     self.assertTrue(job.name.endswith(
         'async.tests.test_deschedule._example'))
     deschedule(_example)
     job = Job.objects.get(pk=job.pk)
     self.assertIsNotNone(job.cancelled)
コード例 #33
0
    def test_adding_job_to_executed_group(self):
        """ Adding a new job to a fully executed group creates a new group.
        """
        self.j1.group = self.g1
        self.j1.executed = timezone.now()
        self.j1.save()

        job = schedule('async.tests.test_models._fn', group=self.g1.reference)
        self.assertEqual(job.group.reference, self.g1.reference)
        self.assertNotEqual(job.group.pk, self.g1.pk)
コード例 #34
0
    def test_model_creattion_with_group(self):
        """make sure schedule API works with group.
        """
        group = Group.objects.create(reference='test-group',
                                     description='for testing')
        job = schedule('async.tests.test_models._fn')
        job.group = group
        job.save()

        self.assertEqual(Job.objects.all().count(), 1)
        self.assertEqual(job.group, group)
コード例 #35
0
ファイル: test_models.py プロジェクト: iamklang/django-async
    def test_adding_job_to_executed_group(self):
        """ Adding a new job to a fully executed group creates a new group.
        """
        self.j1.group = self.g1
        self.j1.executed = timezone.now()
        self.j1.save()

        job = schedule('async.tests.test_models._fn',
            group=self.g1.reference)
        self.assertEqual(job.group.reference, self.g1.reference)
        self.assertNotEqual(job.group.pk, self.g1.pk)
コード例 #36
0
ファイル: test_models.py プロジェクト: iamklang/django-async
    def test_model_creattion_with_group(self):
        """make sure schedule API works with group.
        """
        group = Group.objects.create(
            reference='test-group',
            description='for testing')
        job = schedule('async.tests.test_models._fn')
        job.group = group
        job.save()

        self.assertEqual(Job.objects.all().count(), 1)
        self.assertEqual(job.group, group)
コード例 #37
0
 def test_simple(self):
     """Execute a basic function.
     """
     job = schedule(_function,
         args=['async-test-user'], kwargs={'result': 'something'})
     self.assertEqual(job.execute(), "something")
     self.assertEqual(_EXECUTED,
         (('async-test-user',), {'result': 'something'}))
     self.assertEqual('"something"', job.result)
     self.assertIsNotNone(job.executed)
     self.assertEqual(
         User.objects.filter(username='******').count(), 1)
コード例 #38
0
 def test_unicode_with_args(self):
     """Make sure unicode handling deals with args properly.
     """
     ## ToDo: Fix this later
     try:
         self.assertEqual(
             unicode(
                 schedule('async.tests.test_models._fn',
                          args=['argument'])),
             "async.tests.test_models._fn('argument')")
         self.assertEqual(
             unicode(
                 schedule('async.tests.test_models._fn', args=['a1',
                                                               'a2'])),
             "async.tests.test_models._fn('a1', 'a2')")
         self.assertEqual(
             unicode(schedule('async.tests.test_models._fn', args=[1, 2])),
             'async.tests.test_models._fn(1, 2)')
     except NameError:
         self.assertEqual(
             str(schedule('async.tests.test_models._fn',
                          args=['argument'])),
             "async.tests.test_models._fn('argument')")
         self.assertEqual(
             str(schedule('async.tests.test_models._fn', args=['a1',
                                                               'a2'])),
             "async.tests.test_models._fn('a1', 'a2')")
         self.assertEqual(
             str(schedule('async.tests.test_models._fn', args=[1, 2])),
             'async.tests.test_models._fn(1, 2)')
コード例 #39
0
ファイル: test_models.py プロジェクト: KayEss/django-async
 def test_unicode_with_args_and_kwargs(self):
     """Make sure unicode handling deals with kwargs properly.
     """
     job = schedule('async.tests.test_models._fn',
         args=['argument'], kwargs=dict(k='v', x=None))
     try:
         self.assertEqual(unicode(job),
         "async.tests.test_models._fn('argument', k='v', x=None)")
     except:
         self.assertEqual(str(job),
         "async.tests.test_models._fn('argument', k='v', x=None)")
     self.assertEqual(job.identity,
         '9abc86055107d5b5aa97ea32e098580543680c27')
コード例 #40
0
ファイル: test_models.py プロジェクト: KayEss/django-async
 def test_unicode_with_kwargs(self):
     """Make sure unicode handling deals with kwargs properly.
     """
     job = schedule('async.tests.test_models._fn',
         kwargs=dict(k='v', x=None))
     try:
         self.assertEqual(unicode(job),
         "async.tests.test_models._fn(k='v', x=None)")
     except NameError:
         self.assertEqual(str(job),
         "async.tests.test_models._fn(k='v', x=None)")
     self.assertEqual(job.identity,
         '236a244a0cd845bb5a427db495ec830fa4ab9d93')
コード例 #41
0
 def test_simple(self):
     """Execute a basic function.
     """
     job = schedule(_function,
         args=['async-test-user'], kwargs={'result': 'something'})
     self.assertEqual(job.execute(), "something")
     self.assertEqual(_EXECUTED,
         (('async-test-user',), {'result': 'something'}))
     self.assertEqual('"something"', job.result)
     self.assertIsNotNone(job.executed)
     self.assertLess(job.started, job.executed)
     self.assertEqual(
         User.objects.filter(username='******').count(), 1)
コード例 #42
0
 def test_unicode_with_kwargs(self):
     """Make sure unicode handling deals with kwargs properly.
     """
     job = schedule('async.tests.test_models._fn',
                    kwargs=dict(k='v', x=None))
     try:
         self.assertEqual(unicode(job),
                          "async.tests.test_models._fn(k='v', x=None)")
     except NameError:
         self.assertEqual(str(job),
                          "async.tests.test_models._fn(k='v', x=None)")
     self.assertEqual(job.identity,
                      '236a244a0cd845bb5a427db495ec830fa4ab9d93')
コード例 #43
0
 def post(self, request, response, _app, _model):
     """Wrap the API.
     """
     if hasattr(request.POST, 'getlist'):
         args = request.POST.getlist('args')
     else:
         args = request.POST.get('args', [])
     job = schedule(request.POST['name'],
         args=args,
         kwargs=request.POST.get('kwargs', {}),
         meta=request.POST.get('meta', {}),
         run_after=request.POST.get('run_after', None))
     response['job'] = dict(id=job.id)
コード例 #44
0
 def post(self, request, response, _app, _model):
     """Wrap the API.
     """
     if hasattr(request.POST, 'getlist'):
         args = request.POST.getlist('args')
     else:
         args = request.POST.get('args', [])
     job = schedule(request.POST['name'],
                    args=args,
                    kwargs=request.POST.get('kwargs', {}),
                    meta=request.POST.get('meta', {}),
                    run_after=request.POST.get('run_after', None))
     response['job'] = dict(id=job.id)
コード例 #45
0
ファイル: service.py プロジェクト: SmartRiver/python
    def get(self, request_type):
        if request_type == 'reload':
            try:
                quest_process.__init__()
                match.__init__()
                select_school.__init__()
                schedule.__init__()
                self.write('reloaded.')
            except:
                self.write('failed.')
        elif request_type == 'question_process':
            try:
                quest = smart_unicode(smart_str(self.request.query_arguments['q'][0]))
                result = quest2quest_dict(quest)
            except:
                raise MissingArgumentError('Invalid comment!')
            self.write(json.dumps(result, ensure_ascii=False, indent=4))
        elif request_type == 'find_nearest_offer':
            to_cmp = json.loads(self.request.query_arguments['condition'][0])
            fill_score(to_cmp)
            if 'num' in self.request.query_arguments:
                num = int(self.request.query_arguments['num'][0])
            else:
                num = 5
            offer_id_list = map(
                lambda x: int(x[1]['id']['$numberLong']),
                find_nearest_offer(to_cmp, num)
            )
            self.write(json.dumps(offer_id_list, ensure_ascii=False, indent=4))
        elif request_type == 'find_school':
            to_cmp = json.loads(self.request.query_arguments['condition'][0])
            fill_score(to_cmp)
            if 'num' in self.request.query_arguments:
                num = int(self.request.query_arguments['num'][0])
            else:
                num = 5
            self.write(json.dumps(find_program(to_cmp, num), ensure_ascii=False, indent=4))
        elif request_type == 'assess_applier':
            to_assess = json.loads(self.request.query_arguments['condition'][0])

            self.set_header('Access-Control-Allow-Origin','*')
            self.write(json.dumps(assess_applier(to_assess), ensure_ascii=False, indent=4))

        elif request_type == 'study_schedule':
            to_schedule = json.loads(self.request.query_arguments['condition'][0])

            self.set_header('Access-Control-Allow-Origin','*')
            self.write(json.dumps(schedule(to_schedule), ensure_ascii=False, indent=4))

        else:
            raise MissingArgumentError('Invalid command!')
コード例 #46
0
ファイル: schedulerule.py プロジェクト: abultman/PiAutomator
    def __init__(self, rule_context, rule_state, data, nested_rule):
        """
        @type rule_state: RuleState
        @type data: matplotlib.pyparsing.ParseResults
        """
        weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
        weekenddays = ['saturday', 'sunday']

        super(ScheduleRule, self).__init__(rule_context, rule_state, data,
                                           nested_rule)
        self.scheduleStr = []
        schedule_data = None
        if "pluralSchedule" in data.keys():
            schedule_data = data['pluralSchedule']
        else:
            schedule_data = data['singularSchedule']

        def count():
            if 'count' in schedule_data:
                return schedule_data['count']
            else:
                return 1

        def schedule(unit):
            toeval = "schedule.every(%s).%s" % (count(), unit)
            if "time" in schedule_data.keys():
                toeval = "%s.at('%s')" % (toeval, schedule_data["time"])
            self.scheduleStr.append(toeval)

        unit = schedule_data['unit']
        if unit == 'weekday':
            [schedule(day) for day in weekdays]
        elif unit == 'weekendday':
            [schedule(day) for day in weekenddays]
        elif hasattr(unit, 'asList'):
            [schedule(day) for day in unit.asList()]
        else:
            schedule(unit)
コード例 #47
0
ファイル: schedulerule.py プロジェクト: abultman/PiAutomator
    def __init__(self, rule_context, rule_state, data, nested_rule):
        """
        @type rule_state: RuleState
        @type data: matplotlib.pyparsing.ParseResults
        """
        weekdays = ['monday', 'tuesday', 'wednesday','thursday','friday']
        weekenddays = ['saturday', 'sunday']

        super(ScheduleRule, self).__init__(rule_context, rule_state, data, nested_rule)
        self.scheduleStr = []
        schedule_data = None
        if "pluralSchedule" in data.keys():
            schedule_data = data['pluralSchedule']
        else:
            schedule_data = data['singularSchedule']

        def count():
            if 'count' in schedule_data:
                return schedule_data['count']
            else:
                return 1

        def schedule(unit):
            toeval = "schedule.every(%s).%s" % (count(), unit)
            if "time" in schedule_data.keys():
                toeval = "%s.at('%s')" % (toeval, schedule_data["time"])
            self.scheduleStr.append(toeval)

        unit = schedule_data['unit']
        if unit == 'weekday':
            [schedule(day) for day in weekdays]
        elif unit == 'weekendday':
            [schedule(day) for day in weekenddays]
        elif hasattr(unit, 'asList'):
            [schedule(day) for day in unit.asList()]
        else:
            schedule(unit)
コード例 #48
0
def run_command(command_config, cleaned_data, user):
    if hasattr(command_config, 'get_command_arguments'):
        args, kwargs = command_config.get_command_arguments(cleaned_data)
    else:
        args, kwargs = list(), dict()
    if command_config.asynchronous:
        task = schedule(call_command, [command_config.command_name(), user.pk, args, kwargs])
        return task
    else:
        # Change stdout to a StringIO to be able to retrieve output and
        # display it to the user
        output = StringIO()
        kwargs['stdout'] = output
        management.call_command(command_config.command_name(), *args, **kwargs)
        return output.getvalue()
コード例 #49
0
def run_command(command_config, cleaned_data, user):
    if hasattr(command_config, 'get_command_arguments'):
        args, kwargs = command_config.get_command_arguments(cleaned_data)
    else:
        args, kwargs = list(), dict()
    if command_config.asynchronous:
        task = schedule(call_command,
                        [command_config.command_name(), user.pk, args, kwargs])
        return task
    else:
        # Change stdout to a StringIO to be able to retrieve output and
        # display it to the user
        output = StringIO()
        kwargs['stdout'] = output
        management.call_command(command_config.command_name(), *args, **kwargs)
        return output.getvalue()
コード例 #50
0
 def test_unicode_with_args_and_kwargs(self):
     """Make sure unicode handling deals with kwargs properly.
     """
     job = schedule('async.tests.test_models._fn',
                    args=['argument'],
                    kwargs=dict(k='v', x=None))
     try:
         self.assertEqual(
             unicode(job),
             "async.tests.test_models._fn('argument', k='v', x=None)")
     except:
         self.assertEqual(
             str(job),
             "async.tests.test_models._fn('argument', k='v', x=None)")
     self.assertEqual(job.identity,
                      '9abc86055107d5b5aa97ea32e098580543680c27')
コード例 #51
0
 def post(self, request, response, _app, _model):
     """Wrap the API.
     """
     if hasattr(request.POST, "getlist"):
         args = request.POST.getlist("args")
     else:
         args = request.POST.get("args", [])
     job = schedule(
         request.POST["name"],
         args=args,
         kwargs=request.POST.get("kwargs", {}),
         meta=request.POST.get("meta", {}),
         run_after=request.POST.get("run_after", None),
         priority=request.POST.get("priority", 5),
         group=request.POST.get("group", None),
     )
     response["job"] = dict(id=job.id)
コード例 #52
0
ファイル: test_execute.py プロジェクト: DjNero/django-async
 def test_error_recording(self):
     """Make sure that if there is an error in the function it is dealt
     with properly.
     """
     job = Job.objects.get(
         pk=schedule(_function,
             args=['async-test-user'], kwargs={'assert': False}).pk)
     self.assertEqual(job.errors.count(), 0)
     with self.assertRaises(AssertionError):
         job.execute()
     self.assertEqual(_EXECUTED, (('async-test-user',), {'assert': False}))
     job = Job.objects.get(pk=job.pk)
     self.assertEqual(job.errors.count(), 1)
     error = job.errors.all()[0]
     self.assertIn('AssertionError', error.exception)
     self.assertIn('async/tests/test_execute.py', error.traceback)
     self.assertIsNotNone(job.scheduled)
     self.assertEqual(
         User.objects.filter(username='******').count(), 0)