I want to have a periodic task which creates a todo list.
Then I fire each todo as a separate task.
When the periodic task creates a new todo list, I want to stop the old todo tasks and fire new todo tasks.
I see two problems.
- only
period
functions seem to run. (I guess it's due to thegather
line).- I can't seem to return a value from
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())
I borrowed repeat
code above from https://stackoverflow.com/a/55505152/433570