【发布时间】:2018-03-18 02:19:45
【问题描述】:
我尝试将 python huey 队列合并到我的烧瓶应用程序中,并且我得到了所有的工作。我使用它在我的工作流程中运行任务,并且在任务运行时我将其对用户隐藏(将来自 huey.task 的 task_id 添加到我在数据库中的 taskstatus 中) - 否则看起来同一个任务被卡住了,但实际上它在后台运行。
现在棘手的部分是在 Huey 任务完成时显示我的任务。我像在huey docs中一样合并了事件监听器(通过huey.storage迭代),但据我所知,它订阅redis并无限期运行(因为有定期任务检查)。所以据我了解事件监听器本身必须在单独的线程中运行,所以我写了huey任务来监听huey任务:
@huey.task(include_task=True)
def get_huey_events(task):
from huey.consumer import EVENT_FINISHED
app = create_huey_app('development')
with app.app_context():
# store huey task id and name in database
task1 = HueyTask(task.task_id, task.name)
db.session.add(task1)
db.session.commit()
for event in huey.storage:
if event['status'] == EVENT_FINISHED:
# consume result to remove from storage
result = huey.result(event['id'])
# remove huey id from my task status - inidicates the task finished - my task will be shown to user
status = WorkflowProcessStatuses.query.filter_by(huey_id=event['id']).first()
if status:
status.huey_id = None
db.session.add(status)
db.session.commit()
但是这样说意味着这样的任务只需要运行一次 - 因为它永远消耗一个工人 - 很快就会没有更多的空闲工人。我从 get_huey_events 任务开始,而创建应用程序工厂是这样运行的:
with app.app_context():
task1 = HueyTask.query.filter_by(name='queuecmd_get_huey_events').first()
pipe = redis.StrictRedis()
if task1:
exists = pipe.hexists('huey.tasks', task1.id)
else:
exists = 0
if task1 is None or not exists:
if task1 and not exists:
#clean old task if not running now
pipe.hdel('huey.tasks', task1.id)
db.session.delete(task1)
db.session.commit()
result = get_huey_events()
pipe.hset('huey.tasks',result.task.task_id,'Event listener')
所以我得到了 get_huey_events huey 任务的存储 ID,并查看它是否存储在我自定义创建的 huey.tasks 名称中的 redis 数据库中,并带有 task.id 键。如果数据库中有任务但redis中没有,或者数据库中没有任务,那么我运行事件监听器,否则没有。
我的问题是 - 有没有更好的方法来做到这一点?事件监听器本身应该是一个huey.task吗?我现在在 windows 下运行它。
【问题讨论】:
标签: python events flask listener python-huey