简体   繁体   中英

How to run async function forever (Python)

How do I use asyncio and run the function forever. I know that there's run_until_complete(function_name) but how do I use run_forever how do I call the async function?

async def someFunction():
    async with something as some_variable:
        # do something

I'm not sure how to start the function.

run_forever doesn't mean that an async function will magically run forever, it means that the loop will run forever, or at least until someone calls loop.stop() . To literally run an async function forever, you need to create an async function that does that. For example:

async def some_function():
    async with something as some_variable:
        # do something

async def forever():
    while True:
        await some_function()

loop = asyncio.get_event_loop()
loop.run_until_complete(forever())

This is why run_forever() doesn't accept an argument, it doesn't care about any particular coroutine. The typical pattern is to add some coroutines using loop.create_task or equivalent before invoking run_forever() . But even an event loop that runs no tasks whatsoever and sits idly can be useful since another thread can call asyncio.run_coroutine_threadsafe and give it work.

I'm unsure as to exactly what you mean when you say I'm not sure how to start the function . If you're asking the question in the literal sense:

loop = asyncio.get_event_loop()
loop.run_forever()

If you wish to add a function to the loop before initialising the loop then the following line prior to loop.run_forever() will suffice:

asyncio.async(function())

To add a function to a loop that is already running you'll need ensure_future :

asyncio.ensure_future(function(), loop=loop)

In both cases the function you intend to call must be designated in some way as asynchronous, ie using the async function prefix or the @asyncio.coroutine decorator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM