Пример #1
0
def start_task():
    """ 任务开启 """
    data = request.json
    current_app.logger.info('url:{} ,method:{},请求参数:{}'.format(request.url, request.method, data))
    ids = data.get('id')
    _data = Task.query.filter_by(id=ids).first()

    config_time = change_cron(_data.task_config_time)
    case_ids = []
    if len(json.loads(_data.case_id)) != 0:
        case_ids += [i['id'] for i in json.loads(_data.case_id)]
    else:
        if len(json.loads(_data.case_id)) == 0 and len(json.loads(_data.set_id)) == 0:
            project_id = Project.query.filter_by(name=_data.project_name).first().id
            _set_ids = [_set.id for _set in
                        CaseSet.query.filter_by(project_id=project_id).order_by(CaseSet.num.asc()).all()]
        else:
            _set_ids = [i['id'] for i in json.loads(_data.set_id)]
        for set_id in _set_ids:
            for case_data in Case.query.filter_by(case_set_id=set_id).order_by(Case.num.asc()).all():
                case_ids.append(case_data.id)
    # scheduler.add_job(str(ids), aps_test, trigger='cron', args=['asd'], **config_time)
    project_name = Project.query.filter_by(id=_data.project_id).first().name
    scheduler.add_job(aps_test, 'cron',
                      args=[project_name, case_ids, _data.task_send_email_address, _data.email_password,
                            _data.task_to_email_address],
                      id=str(ids), **config_time)  # 添加任务
    _data.status = '启动'
    db.session.commit()

    return jsonify({'msg': '启动成功', 'status': 1})
Пример #2
0
def start_task():
    data = request.json
    ids = data.get('id')
    _data = Task.query.filter_by(id=ids).first()

    config_time = change_cron(_data.task_config_time)
    case_ids = []
    if len(json.loads(_data.case_id)) != 0:
        case_ids += [i['id'] for i in json.loads(_data.case_id)]
    else:
        if len(json.loads(_data.case_id)) == 0 and len(json.loads(
                _data.set_id)) == 0:
            project_id = Project.query.filter_by(
                name=_data.project_name).first().id
            _set_ids = [
                _set.id for _set in CaseSet.query.filter_by(
                    project_id=project_id).order_by(CaseSet.num.asc()).all()
            ]
        else:
            _set_ids = [i['id'] for i in json.loads(_data.set_id)]
        for set_id in _set_ids:
            for case_data in Case.query.filter_by(case_set_id=set_id).order_by(
                    Case.num.asc()).all():
                case_ids.append(case_data.id)
    # scheduler.add_job(str(ids), aps_test, trigger='cron', args=['asd'], **config_time)
    scheduler.add_job(aps_test,
                      'cron',
                      args=[_data.project_name, case_ids],
                      id=str(ids),
                      **config_time)  # 添加任务
    _data.status = '启动'
    db.session.commit()

    return jsonify({'msg': '启动成功', 'status': 1})
Пример #3
0
def create_order():
    item_id_list = request.json.get('item_list')
    # 地址
    recipient_id = request.json.get('recipient_id')
    recipient = Recipient.query.filter(Recipient.id == recipient_id).one()
    user = get_user()
    order = None
    try:
        order = OrderTable(user_id=user.id,
                           recipient_id=recipient_id,
                           name=recipient.name,
                           phone=recipient.phone,
                           address=recipient.address)
        db.session.add(order)
        db.session.commit()
        for item_id in item_id_list:
            cart_item = CartItem.query.filter(CartItem.id == item_id).one()
            order_item = OrderItem(quantity=cart_item.quantity,
                                   book_id=cart_item.book_id,
                                   price=cart_item.price,
                                   order_id=order.id)
            db.session.add(order_item)
            order.payment_amount += cart_item.price
            db.session.delete(cart_item)
        db.session.commit()
        scheduler.add_job(func=check_overtime,
                          args=[order.id],
                          next_run_time=order.modify_time +
                          TEST_AUTO_CANCEL_TIME)
    except Exception as e:
        db.session.rollback()
        if order:
            db.session.delete(order)
            db.session.commit()
    return render_template('pay.html', order=order)
Пример #4
0
def add_job_interval():
    form = addIntervalForm()
    if form.validate_on_submit():
        # Validate the start date, return empty string if it fails
        try:
            start_date = datetime.strptime(form.start_date.data,
                                           '%Y-%m-%d %H:%M:%S')
        except:
            start_date = ''
        # Check address book for name, use form address data if none found
        address = get_address(form.address.data)
        if address is None:
            address = form.address.data
        # Set job params for scheduler
        job_params = {
            form.int_type.data: int(form.int_val.data),
            'name': form.name.data,
            'start_date': start_date,
            'trigger': 'interval',
            'args': (form.amount.data, address, form.name.data),
            'timezone': timezone(request.cookies.get('tz_name'))
        }
        # Remove empty params from dict
        job_params = remove_empty_keys(job_params)
        # Add job to scheduler
        try:
            scheduler.add_job(send_funds, **job_params)
            print '[%s] Job added: %s' % (str(datetime.now()), job_params)
        except Exception:
            flash('Settings are invalid, please try again')
            return redirect(url_for('add_job_interval'))
        return redirect(url_for('index'))
    return render_template('add_job_interval.html', form=form)
Пример #5
0
def start_task():
    import datetime
    data = request.json
    ids = data.get('id')
    _data = Task.query.filter_by(id=ids).first()
    _data.status = '启动'
    config_time = change_cron(_data.task_config_time)
    # scheduler.add_job(str(ids), aps_test, trigger='cron', args=['asd'], **config_time)
    if _data.task_type == 'cron':
        scheduler.add_job(
            aps_test,
            'cron',
            args=[_data.project_name,
                  json.loads(_data.scene_names)],
            id=str(ids),
            **config_time)  # 添加任务
    else:
        scheduler.add_job(
            aps_test,
            'date',
            args=[
                _data.project_name,
                json.loads(_data.scene_names), 'date', ids
            ],
            id=str(ids),
            run_date=datetime.datetime(
                *[int(t) for t in _data.task_config_time.split(',')]))
    db.session.commit()

    return jsonify({'msg': '启动成功', 'status': 1})
Пример #6
0
def add_job_interval():
    form = addIntervalForm()
    if form.validate_on_submit():
        # Validate the start date, return empty string if it fails
        try:
            start_date = datetime.strptime(form.start_date.data, '%Y-%m-%d %H:%M:%S')
        except:
            start_date = ''
        # Check address book for name, use form address data if none found
        address = get_address(form.address.data)
        if address is None:
            address = form.address.data
        # Set job params for scheduler
        job_params = {form.int_type.data: int(form.int_val.data),
                      'name': form.name.data,
                      'start_date': start_date,
                      'trigger': 'interval',
                      'args': (form.amount.data,
                               address,
                               form.name.data),
                      'timezone': timezone(request.cookies.get('tz_name'))}
        # Remove empty params from dict
        job_params = remove_empty_keys(job_params)
        # Add job to scheduler
        try:
            scheduler.add_job(send_funds, **job_params)
            print '[%s] Job added: %s' % (str(datetime.now()), job_params)
        except Exception:
            flash('Settings are invalid, please try again')
            return redirect(url_for('add_job_interval'))
        return redirect(url_for('index'))
    return render_template('add_job_interval.html',
                           form=form)
Пример #7
0
def start_task():
    """ 任务开启 """
    data = request.json
    ids = data.get('id')
    _data = Task.query.filter_by(id=ids).first()
    config_time = change_cron(_data.task_config_time)
    cases_id = get_case_id(_data.project_id, json.loads(_data.set_id),
                           json.loads(_data.case_id))
    scheduler.add_job(
        func=aps_test,
        trigger='cron',
        misfire_grace_time=60,
        coalesce=False,
        args=[
            _data.project_id, cases_id, _data.task_send_email_address,
            _data.email_password, _data.task_to_email_address,
            User.query.filter_by(id=current_user.id).first().name,
            _data.task_name
        ],
        id=str(ids),
        **config_time)  # 添加任务
    _data.status = '启动'
    db.session.commit()

    return jsonify({'msg': '启动成功', 'status': 1})
Пример #8
0
 def get(self):
     job_id = self.get_query_argument('job_id', None)
     action = self.get_query_argument('action', None)
     if job_id:
         # add
         if 'add' == action:
             if job_id not in JOB_IDS:
                 JOB_IDS.append(job_id)
                 scheduler.add_job(task1,
                                   'interval',
                                   seconds=3,
                                   id=job_id,
                                   args=(job_id, ))
                 self.write('[TASK ADDED] - {}'.format(job_id))
             else:
                 self.write('[TASK EXISTS] - {}'.format(job_id))
         # remove
         elif 'remove' == action:
             if job_id in JOB_IDS:
                 scheduler.remove_job(job_id)
                 JOB_IDS.remove(job_id)
                 self.write('[TASK REMOVED] - {}'.format(job_id))
             else:
                 self.write('[TASK NOT FOUND] - {}'.format(job_id))
     else:
         self.write('[INVALID PARAMS] INVALID job_id or action')
Пример #9
0
def scheduled_task(chat_id, notification_datetime, city):
    bot.bot.send_message(chat_id, weather.get_weather_report(city, 0))
    scheduler.add_job(func=scheduled_task,
                      trigger='date',
                      run_date=notification_datetime,
                      args=[chat_id, notification_datetime, city],
                      id=chat_id)
    scheduler.start()
Пример #10
0
def __add_to_scheduler(uid: ObjectId, entry: MoneyEntry):
    mid = str(entry.id)
    date = entry.date
    scheduler.add_job(__recurring,
                      'date',
                      run_date=date,
                      id=mid,
                      args=[uid, mid])
Пример #11
0
def scheduler_job(job, scheduler=None, cron_change=None):
    if not scheduler:
        from app import scheduler
    scheduler_job_id = 'job_' + str(job.id)
    print('scheduler_job:', job.id, job.is_start, job.mail_id,
          scheduler.get_jobs())
    mail = None
    if scheduler.get_job(
            scheduler_job_id) and not cron_change and job.is_start == 1:
        print('此任务已在执行')
        return

    if job.cron and job.triggers:
        if job.mail_id:
            mail = Mail.query.get(job.mail_id)
        else:
            print('此任务没有配置邮件接收人')
        if job.is_start == 1:
            cron = job.cron.split(' ')
            print(cron)
            if len(cron) != 6:
                print('cron表达式不正确', job.name)
                return
            if cron_change:
                print('定时任务规则改变')

                try:
                    scheduler.remove_job(scheduler_job_id)
                except Exception as e:
                    print(e, '无此任务', job.name)
            scheduler.add_job(id=scheduler_job_id,
                              func=auto_send_mail,
                              trigger=job.triggers,
                              year=cron[5],
                              month=cron[4],
                              day=cron[3],
                              hour=cron[2],
                              minute=cron[1],
                              second=cron[0],
                              args=(job, mail))
            print('get_jobs:', scheduler.get_jobs(),
                  scheduler.get_job(scheduler_job_id))

            print(scheduler.get_job('scheduler_job_id'))

        elif job.is_start == 0:
            print('get_jobs is:', scheduler.get_jobs())
            try:
                scheduler.remove_job(scheduler_job_id)
            except Exception as e:
                print(e, '无此任务', job.name)
                return
            print('get_jobs is_after:', scheduler.get_jobs())
        print('现在有的任务:', scheduler.get_jobs())

    else:
        print('未输入cron表达式或trigger')
        return
Пример #12
0
def startGetInstanceEmojiTask(uri):
    from app import scheduler
    try:
        scheduler.add_job(id='getInstanceEmoji:' + uri,
                          func=getInstanceEmojiWithContext,
                          args=[uri],
                          trigger='date',
                          max_instances=1)
    except apscheduler.jobstores.base.ConflictingIdError:
        pass
Пример #13
0
def init_tasks():
    logger.debug('init tasks')

    add_job(func=run,
            id=f'{cron_env}_JIRA_CAPTURE',
            args=(),
            trigger='cron',
            **from_crontab(config.JIRA_CAPTURE_CRON))
    add_job(func=send,
            id=f'{cron_env}_SEND_CAPTURE',
            args=(),
            trigger='cron',
            **from_crontab(config.SEND_CAPTURE_CRON))
Пример #14
0
def index():
    conn = sqlite3.connect('app.db')
    c = conn.cursor()

    if request.method == 'POST':
        look_for_data()
        scheduler.delete_job('job1')
        scheduler.add_job('job1', look_for_data, trigger='interval', seconds=Config.JOBS[0]['seconds'])

    response = []
    c.execute('SELECT * FROM activo WHERE descargar=? ORDER BY nombre', (1,))
    query = c.fetchall()
    for q in query:
        c.execute('SELECT * FROM cotizacion WHERE activo_id=? ORDER BY fecha DESC LIMIT 2', (q[0],))
        data = c.fetchall()
        if len(data) == 2:
            ticker = q[1]
            nombre = q[2]
            fechaultima = date_to_eu_format(data[0][1])
            VLultimo = data[0][2]
            VLanterior = data[1][2]
            variation = (VLultimo - VLanterior) / VLanterior * 100
            VLultimo = "{0:.4f}".format(VLultimo)
            VLanterior = "{0:.4f}".format(VLanterior)
            fechaanterior = date_to_eu_format(data[1][1])
            variation = "{0:.2f}".format(variation)
            activo_id = q[0]
        elif len(data) == 1:
            ticker = q[1]
            nombre = q[2]
            fechaultima = date_to_eu_format(data[0][1])
            VLultimo = data[0][2]
            VLanterior = ""
            variation = ""
            VLultimo = "{0:.4f}".format(VLultimo)
            fechaanterior = ""
            activo_id = q[0]
        response.append([ticker, nombre, fechaultima, VLultimo, fechaanterior, VLanterior, variation, activo_id])

    c.execute("SELECT * from variables WHERE name=?", ("last_scrape",))
    query = c.fetchone()
    if query is None:
        last_scrape = 0
    else:
        last_scrape = int(float(query[1]))
    next_run_time_epoch = scheduler.get_job('job1').next_run_time.timestamp()
    t_last = datetime.datetime.utcfromtimestamp(last_scrape)
    t_next = datetime.datetime.utcfromtimestamp(next_run_time_epoch)
    data = [t_last, t_next]

    return render_template('index.html', title='Home', table=response, data=data)
Пример #15
0
def add_sync_job(website_type, module_name, class_name, interval):
    from app import scheduler
    job = {
        'id': 'sync_' + website_type,
        'name': "Sync job ",
        'func': "app.task.sync_manager:do_sync_job",
        'args': (website_type, module_name, class_name),
        'trigger': 'interval',
        'seconds': interval,
        'next_run_time': datetime.now(),
        'replace_existing': True,
    }
    scheduler.add_job(**job)
    print("Added sync job:", website_type)
Пример #16
0
 def get(self,id):
     task=Task.query.filter_by(id=id).first()
     if len(task.interface.all())<=1:
         flash(u'定时任务执行过程的测试用例为多用例,请你谅解')
         return  redirect(url_for('home.timingtask'))
     try:
         scheduler.add_job(func=addtask, id=str(id), args=str(id),trigger=eval(task.taskstart),replace_existing=True)
         task.yunxing_status=u'启动'
         db.session.commit()
         flash(u'定时任务启动成功!')
         return  redirect(url_for('home.timingtask'))
     except Exception as e:
         flash(u'定时任务启动失败!请检查任务的各项内容各项内容是否正常')
         return redirect(url_for('home.timingtask'))
Пример #17
0
def handle_disconnecting():
    """
    Handles the disconnecting event. This event is fired before the window unloads.
    Schedules a job to run after WAIT time to perform cleanup if the user doesn't
    rejoin by then.
    """
    if current_user.is_authenticated:
        scheduler.add_job(
            cleanup,
            trigger="date",
            args=[current_user.sid],
            next_run_time=(datetime.datetime.now() +
                           datetime.timedelta(seconds=10)),
        )
Пример #18
0
def recurring_execution(src_id, tgt_id, money, description, period, date_arr):
    src_acc = Account.query.get(src_id)
    tgt_acc = Account.query.get(tgt_id)
    src = User.query.get(src_acc.user_id)
    tgt = User.query.get(tgt_acc.user_id)
    date = datetime_str(date_arr)
    job_id = ''
    name = ''
    # generate the recurring job id
    if src.id == tgt.id:
        job_id += ('Internal' + str(src_acc.id) + str(tgt_acc.id) + str(date))
        name += ('Internal recurring: from ' + src_acc.type + ' to '
                 + tgt_acc.type + ', ' + period + ', starting on ' + str(date)
                 + ', amount: $' + str(money))
    else:
        job_id += ('Wire' + str(src_acc.id) + str(tgt_acc.id) + str(date))
        name += ('Wire recurring: to ' + tgt.first_name + ' '
                 + tgt.last_name + ', ' + period + ', starting on ' + str(date)
                 + ', amount: $' + str(money))
    # generate different recurring tasks
    if period == 'demo':
        scheduler.add_job(id=job_id, name=name,
                          func=recurring_transaction_generator,
                          trigger='interval',
                          seconds=5, args=[src_id, tgt_id, money, description, 'recurring demo'])
    elif period == 'daily':
        scheduler.add_job(id=job_id, name=name,
                          func=recurring_transaction_generator,
                          trigger='cron',
                          day='*', hour=5, minute=30, args=[src_id, tgt_id, money, description, 'daily recurring wire'])
    elif period == 'weekly':
        weekday = weekday_calculator(date_arr)
        scheduler.add_job(id=job_id, name=name,
                          func=recurring_transaction_generator,
                          trigger='cron',
                          day_of_week=weekday, hour=5, minute=30,
                          args=[src_id, tgt_id, money, description, 'weekly recurring wire'])
    elif period == 'monthly':
        scheduler.add_job(id=job_id, name=name,
                          func=recurring_transaction_generator,
                          trigger='cron',
                          month='*', day=date_arr[2], hour=5, minute=30,
                          args=[src_id, tgt_id, money, description, 'weekly recurring wire'])
    else:
        scheduler.add_job(id=job_id, name=name,
                          func=recurring_transaction_generator,
                          trigger='cron',
                          year='*', month=date_arr[1], day=date_arr[2], hour=5, minute=30,
                          args=[src_id, tgt_id, money, description, 'weekly recurring wire'])
Пример #19
0
def initialize_cache():
    from config import Config
    from app.api.events_cache import refresh_cache_thread, refresh_cache
    from app import scheduler, current_app

    # we'll set the run interval just little less than the CACHE TIMEOUT to avoid
    # the refresh be > CACHE_TIMEOUT
    logger.debug("initializing cache")
    refresh_cache(True)
    logger.debug("starting refresh thread")
    scheduler.add_job(refresh_cache_thread,
                      'interval',
                      seconds=Config.CACHE_TIMEOUT - 10,
                      args=[current_app._get_current_object()])
    scheduler.start()
Пример #20
0
def add_job(id, interval, type='html'):
    if type == 'html':
        task_id = id
    elif type == 'rss':
        task_id = 'rss{}'.format(id)

    scheduler.add_job(func=monitor,
                      args=(
                          id,
                          type,
                      ),
                      trigger='interval',
                      minutes=interval,
                      id='task_{}'.format(task_id),
                      replace_existing=True)
    logger.info('添加task_{}'.format(task_id))
Пример #21
0
def order_complete(order_id):
    order = OrderTable.query.filter(
        and_(OrderTable.user_id == get_user().id,
             OrderTable.id == order_id)).one_or_none()
    if order.state == OrderState.WaitReceive.value:
        order.state = OrderState.Received.value
        order.modify_time = datetime.now()
        scheduler.add_job(func=check_overtime,
                          args=[order.id],
                          next_run_time=order.modify_time +
                          TEST_AUTO_FINISH_TIME)
        for item in order.order_items:
            item.book.sales_volume += item.quantity
        db.session.commit()
    else:
        abort(404)
    return redirect(url_for('order_detail', order_id=order_id))
Пример #22
0
def update_game_results(game_id):
    """Update game details and result, create scheduler"""
    result = get_game(game_id)
    game = save_game(game_id, result)
    if not game.end_of_game:
        game = get_results(game.game_id)

    if not game.end_of_game:
        game_id_str = str(game.game_id)
        job = scheduler.get_job(game_id_str)
        if job is None:
            scheduler.add_job(id=game_id_str,
                              func=update_game_results,
                              args=[game.game_id],
                              trigger="interval",
                              days=1,
                              start_date=game.next_day_time +
                              timedelta(minutes=5))
Пример #23
0
def startup():
    name = request.values['name'] if 'name' in request.values else ''
    extendJobDefine = JobDefine.objects((Q(name=name))).first()

    if extendJobDefine is None:
        return XaResult.error(msg=u'请提供正确且存在的任务名称')
    try:
        cron = CronTrigger.from_crontab(extendJobDefine.jobCron)

        scheduler.add_job(id=name,
                          func=job_task_load.to_job_instance,
                          trigger=cron,
                          args=(name, ))
        JobDefine.objects(name=name).update_one(isRun=True)
        app.logger.info(u'%s 任务启动成功!', name)
    except Exception, e:
        app.logger.error(u'%s 任务启动失败!错误信息:%s', name, e.message)
        return XaResult.error(msg=e.message)
Пример #24
0
def reload_runnable_spider_job_execution():
    '''
    add periodic job to scheduler
    :return:
    '''
    running_job_ids = set([job.id for job in scheduler.get_jobs()])
    # app.logger.debug('[running_job_ids] %s' % ','.join(running_job_ids))
    available_job_ids = set()
    # add new job to schedule
    for job_instance in JobInstance.query.filter_by(enabled=0,
                                                    run_type="periodic").all():
        job_id = "spider_job_%s:%s" % (
            job_instance.id,
            int(time.mktime(job_instance.date_modified.timetuple())))
        available_job_ids.add(job_id)
        if job_id not in running_job_ids:
            try:
                scheduler.add_job(run_spider_job,
                                  args=(job_instance.id, ),
                                  trigger='cron',
                                  id=job_id,
                                  minute=job_instance.cron_minutes,
                                  hour=job_instance.cron_hour,
                                  day=job_instance.cron_day_of_month,
                                  day_of_week=job_instance.cron_day_of_week,
                                  month=job_instance.cron_month,
                                  second=0,
                                  max_instances=999,
                                  misfire_grace_time=60 * 60,
                                  coalesce=True)
            except Exception as e:
                app.logger.error(
                    '[load_spider_job] failed {} {},may be cron expression format error '
                    .format(job_id, str(e)))
            app.logger.info(
                '[load_spider_job][project:%s][spider_name:%s][job_instance_id:%s][job_id:%s]'
                % (job_instance.project_id, job_instance.spider_name,
                   job_instance.id, job_id))
    # remove invalid jobs
    for invalid_job_id in filter(
            lambda job_id: job_id.startswith("spider_job_"),
            running_job_ids.difference(available_job_ids)):
        scheduler.remove_job(invalid_job_id)
        app.logger.info('[drop_spider_job][job_id:%s]' % invalid_job_id)
Пример #25
0
 def start(self):
     """Start job"""
     if self.job is None:
         self.job = scheduler.add_job(
             id="market_%s" % self.game_id,
             func=run,
             args=[self.game.game_id, "market"],
             trigger="interval",
             hours=1,
         )
Пример #26
0
 def start(self):
     """Start job for game"""
     if self.job is None:
         self.job = scheduler.add_job(id=self.game_id,
                                      func=run,
                                      args=[self.game.game_id],
                                      trigger="interval",
                                      days=1,
                                      start_date=self.game.next_day_time +
                                      timedelta(minutes=5))
Пример #27
0
    def post(self):
        """
        添加监控周期任务
        """
        args = self.parse_args(add_scheduler_fields)
        scope_id = args.pop("scope_id")
        domain = args.pop("domain")
        interval = args.pop("interval")
        name = args.pop("name")

        if interval < 3600 * 6:
            return utils.build_ret(ErrorMsg.IntervalLessThan3600,
                                   {"interval": interval})

        monitor_domain = utils.arl.get_monitor_domain_by_id(scope_id)
        scope_data = utils.arl.scope_data_by_id(scope_id)

        if not scope_data:
            return utils.build_ret(ErrorMsg.NotFoundScopeID,
                                   {"scope_id": scope_id})

        domains = domain.split(",")
        for x in domains:
            curr_domain = x.strip()
            if curr_domain not in scope_data["scope_array"]:
                return utils.build_ret(ErrorMsg.DomainNotFoundViaScope, {
                    "domain": curr_domain,
                    "scope_id": scope_id
                })

            if curr_domain in monitor_domain:
                return utils.build_ret(ErrorMsg.DomainViaJob, {
                    "domain": curr_domain,
                    "scope_id": scope_id
                })

        ret_data = []
        for x in domains:
            curr_name = name
            if not name:
                curr_name = "监控-{}-{}".format(scope_data["name"], x)

            job_id = app_scheduler.add_job(domain=x,
                                           scope_id=scope_id,
                                           options=None,
                                           interval=interval,
                                           name=curr_name)
            ret_data.append({
                "domain": x,
                "scope_id": scope_id,
                "job_id": job_id
            })

        return utils.build_ret(ErrorMsg.Success, ret_data)
Пример #28
0
def order_update(order_id):
    order = OrderTable.query.filter(OrderTable.id == order_id).one()
    if order:
        order.state = request.form.get('state')
        order.modify_time = datetime.now()
        if order.state == OrderState.Returned.value:
            for item in order.order_items:
                item.book.sales_volume -= item.quantity
            refund(order)
        db.session.commit()
        if order.state == OrderState.WaitReceive.value:
            run_time = order.modify_time + TEST_AUTO_CONFIRM_TIME
            # if run_time >= datetime.now():
            #     run_time = datetime.now() + TEST_AUTO_CONFIRM_TIME
            scheduler.add_job(func=check_overtime,
                              args=[order.id],
                              next_run_time=run_time)
    else:
        abort(404)
    return redirect(url_for('admin_order_detail', order_id=order_id))
Пример #29
0
def suggested_question_pdf(user_id):
    data = request.data

    data = data.decode('utf8').replace("'", '"')
    run_time = datetime.now() + timedelta(0, 300)
    if data is None or data == '':
        return jsonify({
            'code': 400,
            "message": "data is unavailable",
            "status": 'failed'
        })
    try:
        json_obj = json.loads(data)
    except Exception as e:
        print(e)
        return jsonify({
            'code': 400,
            "message": "Invalid data only json data accepted",
            "status": 'failed'
        })
    job_exist = scheduler.get_job(user_id)
    if job_exist is None:
        scheduler.add_job(job,
                          'date',
                          run_date=run_time,
                          id=str(user_id),
                          kwargs={
                              'user_id': user_id,
                              'json_obj': data
                          })
    else:
        scheduler.remove_job(str(user_id))
        scheduler.add_job(job,
                          'date',
                          run_date=run_time,
                          id=str(user_id),
                          kwargs={
                              'user_id': user_id,
                              'json_obj': data
                          })
    return jsonify({'code': 200, "result": [], "status": 'success'})
    def new(parameters, files=None):
        # See if check name is not duplicate for this course
        if not Check.query.filter_by(
                name=parameters['name'],
                course_id=parameters['course_id']).first():
            # Create a new entry (record) for checks table and save to db

            check = Check(parameters['name'], int(parameters['course_id']),
                          parameters['language'], parameters['start_date'],
                          parameters['end_date'], parameters['interval'], True)
            db.session.add(check)
            db.session.commit()
            scheduler.add_job(func=ChecksController.run,
                              trigger="interval",
                              hours=check.interval,
                              args=[check.id],
                              start_date=check.start_date,
                              end_date=check.end_date)
            # scheduler.add_job(func = ChecksController.run, trigger = "interval", hours = 1, args = [1], next_run_time=datetime.now())

        else:
            # Raise value error if duplicate check name for this course
            raise ValueError(
                "Check name '{}' for course {} already exists.".format(
                    parameters['name'], parameters['course_id']))

        curr_check = Check.query.filter_by(
            name=parameters['name'],
            course_id=parameters['course_id']).first()
        if curr_check:
            duplicates = SubmissionController.new(
                {
                    'check_id': curr_check.id,
                    'header': parameters['header']
                }, submissionsCSV)
        PathsController.new(
            {
                'check_id': curr_check.id,
                'header': parameters['header']
            }, pathsCSV)
Пример #31
0
def add_job_cron():
    form = addCronForm()
    if form.validate_on_submit():
        # Reject if at least one cron trigger is not set
        if not form.year.data and not form.month.data \
           and not form.day.data and not form.week.data \
           and not form.day_of_week.data and not form.hour.data \
           and not form.minute.data:
            flash('You must include at least one cron trigger')
            return redirect(url_for('add_job_cron'))
        # Check address book for name, use form.address.data if none found
        address = get_address(form.address.data)
        if address is None:
            address = form.address.data
        # Set job params for scheduler
        job_params = {'name': form.name.data,
                      'year': form.year.data,
                      'month': form.month.data,
                      'day': form.day.data,
                      'week': form.week.data,
                      'day_of_week': form.day_of_week.data,
                      'hour': form.hour.data,
                      'minute': form.minute.data,
                      'trigger': 'cron',
                      'args': (form.amount.data,
                               address,
                               form.name.data),
                      'timezone': timezone(request.cookies.get('tz_name'))}
        # Remove empty params from dict
        job_params = remove_empty_keys(job_params)
        # Add job to scheduler
        try:
            scheduler.add_job(send_funds, **job_params)
            print '[%s] Job added: %s' % (str(datetime.now()), job_params)
        except Exception:
            flash('Settings are invalid, please try again')
            return redirect(url_for('add_job_cron'))
        return redirect(url_for('index'))
    return render_template('add_job_cron.html',
                           form=form)
Пример #32
0
def add_job(task):
    """
    新增任务
    """
    trigger = task.trigger
    # 验证任务类型
    if trigger == 'interval':
        scheduler.add_job(id=str(task.id),
                          func=task_run,
                          name=task.name,
                          trigger=trigger,
                          seconds=int(task.time),
                          args=(task, ),
                          replace_existing=True)
    elif trigger == 'date':
        scheduler.add_job(id=str(task.id),
                          func=task_run,
                          name=task.name,
                          trigger=trigger,
                          next_run_time=datetime.datetime.utcnow() +
                          datetime.timedelta(seconds=int(task.time)),
                          args=(task, ),
                          replace_existing=True)
    elif trigger == 'cron':
        scheduler.add_job(id=str(task.id),
                          func=task_run,
                          name=task.name,
                          trigger=trigger,
                          second=task.time,
                          args=(task, ),
                          replace_existing=True)