我在Aiohttp有一个Web应用程序。
如何管理长时间运行的任务?我看到了这种情况。这是坏事还是好事?
new_task = asyncio.create_task()
创建任务为新任务生成uuid并将其全部保存在dict中:new_task = asyncio.create_task()
uuid_task = uuid.uuid4()
tasks_set.update({
uuid_task: new_task
})
tasks_set
中查找任务并获取状态:task = tasks_set.get(uuid_from_client)
if not task:
raise TaskNotFound # send error, 404 for example
if not task.done():
# task is not done yet
answer_to_client('task is not done')
return
else:
answer_to_client('task is done. Result: ', task.result())
tasks_set.pop(uuid_from_client)
但我还必须管理任务的超时(用户已经离开,我们应该停止他的任务)。有什么建议吗?
但我还必须管理任务的超时
您可以使用asyncio.wait_for
为任何协同程序添加超时。代替:
# run coroutine in a new task
new_task = asyncio.create_task(coroutine(...))
您可以使用:
# run coroutine in a new task, for no longer than 10s
new_task = asyncio.create_task(asyncio.wait_for(coroutine(...), 10)
如果协程完成并且超时,new_task.done()
将是真的。您可以通过测试new_task.done() and new_task.exception() is asyncio.TimeoutError
来测试超时。