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
def change_task_status(status, id): """ 改变任务状态 (('add', '启动'), ('pause', '暂停'), ('run', '运行'), ('stop', '停止')) """ # 验证任务是否存在 task = Task.objects(id=id).first() if not task: flash('任务不存在') else: # 验证状态 if status not in ('add', 'pause', 'run', 'stop'): flash('无效任务状态[' + status + ']') return redirect(url_for('core.tasks')) if status == 'add': add_job(task) else: job = scheduler.get_job(id) if not job: flash('任务未启动') return status if status == 'run': scheduler.resume_job(id) elif status == 'pause': scheduler.pause_job(id) elif status == 'stop': scheduler.remove_job(id) flash('操作成功') return status
def update_task_status(self, task): # 更新任务状态。 job = scheduler.get_job(task.id) if job and job.next_run_time.timestamp() > time.time(): if task.task_status == 0: task.task_status = 1 # 运行中 task.update() else: task.task_status = 3 # 已完成 task.update()
def tasks(): """ 任务列表 """ page = request.args.get('page', 1, type=int) pagination = Task.objects.order_by("-create_time").paginate( page=page, per_page=current_app.config['PER_PAGE_10']) tasks = pagination.items for task in tasks: task.job = scheduler.get_job(str(task.id)) return render_template('core/tasks.html', tasks=tasks, pagination=pagination)
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)
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))
def save_game(game_id, result): """Save game results in database""" game = Game.query.filter(Game.game_id == game_id).first() if game.start_at is None: save_new_game(game, result) game.number_of_players = result["numberOfPlayers"] - result["openSlots"] game.end_of_game = result["endOfGame"] game.day_of_game = result["dayOfGame"] game.next_day_time = datetime.fromtimestamp(result["nextDayTime"] / 1000) if game.end_of_game: job = scheduler.get_job(str(game.game_id)) if job is not None: job.remove() db.session.commit() return game
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 check_response(game_id, response): """Check for correct response""" if response["result"]["@c"] == "ultshared.rpc.UltSwitchServerException": game = Game.query.filter(Game.game_id == game_id).first() if "newHostName" in response["result"]: print("new host: " + response["result"]["newHostName"]) game.game_host = "http://" + response["result"]["newHostName"] db.session.commit() else: print("Game does not exist") game.end_of_game = True game.end_at = datetime.now() db.session.commit() job = scheduler.get_job(str(game.game_id)) if job is not None: job.remove() raise GameDoesNotExistError("Game %s is not found" % game_id + \ "on the Supremacy 1914 server") return False return True
def start_send_email_task(): running_job = scheduler.get_job('send_email_task') if running_job: scheduler.remove_job('send_email_task') scheduler.add_job('send_email_task', send_email_task)
def __init__(self, game): """Initialize MarketJob""" BaseJob.__init__(self, game) self.job = scheduler.get_job("market_%s" % self.game_id)
def __init__(self, game): """Initialize Job""" BaseJob.__init__(self, game) self.game_id = str(game.game_id) self.job = scheduler.get_job(self.game_id)