user13824551
user13824551

Reputation: 97

Running an asynchronous function 'in the background'

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()

Upvotes: 5

Views: 14300

Answers (2)

user4815162342
user4815162342

Reputation: 154846

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.

Upvotes: 7

El Sampsa
El Sampsa

Reputation: 1733

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.

Upvotes: 0

Related Questions