asyncio,周期性任务并获取返回值



我想要一个创建待办事项列表的周期性任务。

然后我把每个todo作为一个单独的任务来启动。

当周期性任务创建一个新的待办事项列表时,我想停止旧的待办事项并启动新的待办任务。

我看到两个问题。

  1. 似乎只有period函数在运行。(我想是由于gather线路(
  2. 我似乎无法从do_todo返回值
import asyncio
async def repeat(interval, func, *args, **kwargs):
    while True:
        await asyncio.gather(
            func(*args, **kwargs),
            asyncio.sleep(interval),
        )

async def create_todo():
    await asyncio.sleep(1)
    print('Hello')
    todos = list(range(3))
    return todos
async def g():
    await asyncio.sleep(0.5)
    print('Goodbye')
    return 2
async def do_todo(x ):
    await asyncio.sleep(0.5)
    print(f'do something with {x}')
async def main():
    create_todo_task = asyncio.create_task(repeat(3, create_todo))
    another_task = asyncio.create_task(repeat(2, g))
    todos = await create_todo_task
    print('todos', todos)
    res2 = await another_task
    print('g result', res2)
    for todo in todos:
        t3 = asyncio.create_task(do_todo(todo))
        await t3
asyncio.run(main())

我借用了上面的repeat代码https://stackoverflow.com/a/55505152/433570

这是一个永远不会返回的无限循环:

async def repeat(interval, func, *args, **kwargs):
    while True:
        await func(*args, **kwargs)

当你写

todos = await create_todo_task

你在等待你的无限循环结束,这显然是永远不会发生的。

对于您的第二个问题:您的do_todo没有返回语句。你期望的回报值是多少?或者你的意思是print没有被调用?如果是,请参阅第一个问题的答案。

最新更新