5

I have several asynchronous functions. If I call main(), I can't use the second check() function, because main() runs continuously in a while loop. Can I run main() 'in the background' to make the rest of the functions available?

import asyncio

async def main():
    while True:
        # update database

async def check():
    # confirm update

async def process(command):
    if command == "main":
        await main()
    elif command == "check":
        await check()
2
  • To make them available to what? Where do you want to call them from? Commented Jan 26, 2021 at 16:16
  • @RandomDavis main and` check` are bot commands Commented Jan 27, 2021 at 9:17

2 Answers 2

7

Can I run main() 'in the background' to make the rest of the functions available?

Yes, you can replace await main() with asyncio.create_task(main()). That will spawn main as a task that effectively runs in the background.

Sign up to request clarification or add additional context in comments.

As noted in the docs for create_task, you should save a reference to the result of create_task function, to avoid task disappearance mid-execution due to possible garbage collection.
0

What you're really asking, is how to achieve concurrency (several coroutines/"things" running simultaneously). You can achieve concurrency using background tasks as the first answer suggests.

However, that strategy ends up easily in a mess (well, concurrency always ends up in mess): you might get "runaway" background tasks you didn't know are still running, background tasks that manipulate the same data structures, resulting in surprises, your program's logic might also depend if tasks are finished or not (in order to fire up different tasks) and then you start messing around with asyncio.wait and asyncio.gather. It's a road to hell, really.

So, I'm advertising here shamelessly a thing I wrote in order to solve these issues: TaskThread. It's been a real life safer: you can run tons of simultaneous background tasks, but they are under control & well organized.

TaskThread seems to be similar to asyncio.TaskGroup from Python 3.11 to me.
Thanks for the tip! But TaskThread is so much more than just waiting for a bunch of tasks simultaneously. :)

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.