Beispiel #1
0
def botAddBlameJob(data):

    message = 'Такого игрока не существует'

    user_id = int(data['text'].split()[1])

    player = Player.query.filter_by(user_id=user_id).first()

    if player:
        jobName = playerAlarmName + str(player.user_id)
        run_date = player.date.replace(hour=15, minute=0, second=0, microsecond=0) + timedelta(weeks=3)

        message = 'Для ' + player.name + ' добавлена напоминалка на ' +\
                  run_date.strftime('%d/%m/%Y, %H:%M:%S') + ' UTC+0'

        scheduler.add_job(
            send_blame_message,
            'date',
            run_date=run_date,
            args=[data['group_id'], player.user_id, 2000000003],
            id=jobName,
            jobstore='default'
        )

    return message, ''
Beispiel #2
0
def create_crawler_task(app):
    # 定时抓取数据
    scheduler.add_job(func=update_data,
                      id="update_data",
                      trigger="cron",
                      hour=app.config['HOUR'],
                      minute=app.config['MINUTE'])
Beispiel #3
0
    def get(self):
        response_data = deepcopy(self.base_response_data)
        scheduler.add_job(func=update_data,
                          id="start_crawler",
                          trigger="date",
                          next_run_time=datetime.datetime.now() +
                          datetime.timedelta(seconds=5))

        return response_data, 200
Beispiel #4
0
def add_job(**kwargs):
    response = {'status': False}
    try:
        scheduler.add_job(**kwargs)
        response['status'] = True
        response['msg'] = "job[%s] addjob success!" % id
        add_task(**kwargs)
        print("添加一次性任务成功---[ %s ] " % id)
    except Exception as e:
        response['msg'] = str(e)
def startWeekNotification(data):

    peer_id = data['peer_id']

    jobName = weeklyJobName + str(peer_id)

    job = scheduler.get_job(job_id=jobName, jobstore='default')

    if job is not None:
        message = 'Для этой беседы оповещение уже создано. Если вы хотите отменить существующее, то напишите ' \
                  '"Адик, останови 7 дней", чтобы запустить новое оповещение.'
        return message, ''

    text = data['text'].split(' ')

    day = text[-2]
    hour = int(text[-1].split(':')[0]) - 3

    message = 'Запускаю недельные оповещения. Дата оповещения: ' + day + ' в ' + text[
        -1] + '.'

    if hour < 0:
        hour = 24 + hour

        dayList = list(daysDict.keys())
        day = dayList[dayList.index(day) - 1]

    minute = int(text[-1].split(':')[1])

    job_id = weeklyJobName + str(peer_id)

    scheduler.add_job(send_list,
                      'cron',
                      day_of_week=daysDict.get(day),
                      hour=hour,
                      minute=minute,
                      args=[peer_id],
                      id=job_id,
                      jobstore='default')
    scheduler.print_jobs(jobstore='default')

    return message, ''
Beispiel #6
0
def check_blame_alarm(player, data):

    # находим в списке работ ту, что player_alarm+player_id
    jobName = playerAlarmName+str(player.user_id)

    try:
        scheduler.remove_job(job_id=jobName, jobstore='default')
    except JobLookupError:
        print("No job by the id of player_alarm202941722")

    run_date = player.date.replace(hour=15, minute=0, second=0, microsecond=0) + datetime.timedelta(weeks=3)

    scheduler.add_job(
        send_blame_message,
        'date',
        run_date=run_date,
        args=[data['group_id'], player.user_id, data['peer_id']],
        id=jobName,
        jobstore='default'
    )
Beispiel #7
0
 def put(self):
     response_data = deepcopy(self.base_response_data)
     # answer_zhihuid = self.parser.parse_args().get('answerZhiHuId')
     # 问题id
     # question_zhihuid = self.parser.parse_args().get('questionZhiHuId')
     answer_url = self.parser.parse_args().get('answerUrl')
     question_zhihuid, answer_zhihuid = re.findall(
         r".*question/(.*)/answer/(.*)", answer_url)[0]
     question_zhihuid, answer_zhihuid = int(question_zhihuid), int(
         answer_zhihuid)
     is_success, question_data = self.requester.get_question_by_zhihuid(
         question_zhihuid)
     if is_success:
         # 数据库中的id
         question_id = question_data.id
         is_success = self.add_new_answer(
             answer_zhihuid=answer_zhihuid,
             question_zhihuid=question_zhihuid,
             question_id=question_id,
             question_title=question_data.title,
             user_id=g.user.id)
         # 回答在数据库的数据
         _, answer_data = self.requester.get_answer_by_zhihuid(
             answer_zhihuid, question_zhihuid)
         # answer_id为数据库的id
         answer_id = answer_data.id
         scheduler.add_job(
             func=add_new_answer_crawler,
             id="add_new_answer_crawler",
             trigger="date",
             next_run_time=datetime.datetime.now() +
             datetime.timedelta(seconds=5),
             args=[question_zhihuid, answer_zhihuid, answer_id])
         return response_data, 200
     else:
         response_data['res'] = 0
         response_data['message'] = "error"
         return response_data
Beispiel #8
0
def add_cron():
    job = {}
    response = {'status': False}
    jobargs = request.get_json()
    id = jobargs['task_id']
    name = jobargs['task_name']
    trigger_type = jobargs['trigger_type']
    if trigger_type == "date":
        run_time = jobargs['run_time']

        try:
            scheduler.add_job(jobstore='default',
                              func='app.task.test_task:my_job',
                              trigger=trigger_type,
                              run_date=run_time,
                              replace_existing=True,
                              coalesce=True,
                              id=id,
                              name=name,
                              max_instances=1)
            response['status'] = True
            response['msg'] = "job[%s] addjob success!" % id
            add_task(jobargs)
            print("添加一次性任务成功---[ %s ] " % id)

        except Exception as e:
            response['msg'] = str(e)

    elif trigger_type == 'interval':
        seconds = jobargs['interval_time']
        seconds = int(seconds)
        if seconds <= 0:
            raise TypeError('请输入大于0的时间间隔!')
        try:
            scheduler.add_job(jobstore='default',
                              func='app.task.test_task:my_job',
                              trigger=trigger_type,
                              seconds=seconds,
                              replace_existing=True,
                              coalesce=True,
                              id=id,
                              name=name,
                              max_instances=1)
            response['status'] = True
            add_task(jobargs)
            print("添加周期执行任务成功任务成功---[ %s ] " % id)
        except Exception as e:
            response['msg'] = str(e)

    elif trigger_type == "cron":
        day_of_week = jobargs["run_time"]["day_of_week"]
        hour = jobargs["run_time"]["hour"]
        minute = jobargs["run_time"]["minute"]
        second = jobargs["run_time"]["second"]
        try:
            scheduler.add_job(jobstore='default',
                              func='app.task.test_task:my_job',
                              id=id,
                              name=name,
                              trigger=trigger_type,
                              day_of_week=day_of_week,
                              hour=hour,
                              minute=minute,
                              second=second,
                              replace_existing=True,
                              max_instances=1)
            response['status'] = True
            add_task(jobargs)
            print("添加周期执行任务成功任务成功---[ %s ]" % id)
        except Exception as e:
            response['msg'] = str(e)
    return jsonify({"status": 200, "data": "success", 'response': response})