Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

python - 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(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()
question from:https://stackoverflow.com/questions/65904964/running-an-asynchronous-function-in-the-background

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...