def get_task(target): with lock: task_count = tuple(v.user_name for v in task_pool.values() if v.target == target).count(session['user_name']) t = render_template('layout.html', text=f'{task_count} active tasks for {target}.') return t
def get_notifications(): with lock: task_count = len( tuple(1 for v in task_pool.values() if v.state in ('wait', 'run'))) t = render_template( 'static_list.html', text=f'{task_count} tasks are active. ' f'Only last {app.config["MAX_KEPT_NOTIFICATIONS"]} task messages will be kept.', data=notification_pool) return t
def run(self): while self.active: # Now dnd means "send with no sound". Formerly tasks did were't processing at dnd hours. # if check_dnd_time(): # sleep(app.config['WORKER_FREQ_SEC']) # continue with lock: active_tasks = tuple(t for t in sorted(task_pool.values(), key=lambda x: x.priority) if t.state == 'wait') for task in active_tasks: with lock: if not task_pool.get(task.uuid): continue if task.last_call: pt = task.period[-1:] pv = task.period[:-1] next_call = task.last_call + get_offset(pv, pt) if next_call > datetime.now(): continue task.state = 'run' try: task_start_time = datetime.now() message = app.view_functions[task.endpoint](task) r = 0 if message: if task.text: message = f'{t_italic(task.text)}\n{message}' notification_pool.appendleft( (datetime.now(), task.uuid, task.name, message)) if task.chat_id and not app.config['MUTE_MESSAGES']: r = prepare_and_send(task.chat_id, task.reply_to_message_id, message, task.sound) if r != 0: unsent_pool.appendleft( (datetime.now(), task.uuid, task.name, task.chat_id, task.reply_to_message_id, message)) if task.finished: del task_pool[task.uuid] else: task.last_call = datetime.now() task.duration = (task.last_call - task_start_time).seconds task.execs += 1 task.state = 'wait' if r == 0 or not app.config[ 'FAIL_TASK_ON_MSG_ERROR'] else 'msg error' # retry sending even if prev msg had no recipient if r == 0 and message and not app.config['MUTE_MESSAGES']: while r == 0 and len(unsent_pool) > 0: m = unsent_pool.popleft() r = prepare_and_send( m[3], m[4], f'{t_italic("This message was postponed due to network problem")}' f'\n{m[5]}', 'default') if r == 0 and task_pool.get(m[1], None): task_pool[m[1]].state = 'wait' if r != 0: unsent_pool.appendleft(m) except (DatabaseError, OperationalError) as e: app.logger.error(f'{task.uuid} {e.args[0].message}') task.state = 'db error' sleep(app.config['WORKER_FREQ_SEC'])