我想要一个创建待办事项列表的周期性任务。
然后我把每个todo作为一个单独的任务来启动。
当周期性任务创建一个新的待办事项列表时,我想停止旧的待办事项并启动新的待办任务。
我看到两个问题。
- 似乎只有
period
函数在运行。(我想是由于gather
线路(- 我似乎无法从
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
没有被调用?如果是,请参阅第一个问题的答案。