Running an asynchronous function 'in the background'

Viewed 3549

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(self):
    while True:
        ...
        Update database
        ...


async def _check(self):
    await self._confirm_update()


async def process(self):
    if self.command in ["main"]:
        await self._main()
    elif self.command in ["check"]:
        await self._check()
2 Answers

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

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

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.

Related