0

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.

  1. only period functions seem to run. (I guess it's due to the gather line).
  2. 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

eugene
  • 39,839
  • 68
  • 255
  • 489

1 Answers1

0

This is an infinite loop that never returns:

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

When you write

todos = await create_todo_task

you are waiting for your infinite loop to finish, which obviously never happens.

For your second question: Your do_todo doesn't have a return statement. What return value do you expect? Or do you mean the print isn't called? If so, see answer to your first question.

thisisalsomypassword
  • 1,423
  • 1
  • 6
  • 17