Tearzz
Tearzz

Reputation: 321

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.

Upvotes: 1

Views: 17082

Answers (2)

user4815162342
user4815162342

Reputation: 154846

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.

Upvotes: 6

amitchone
amitchone

Reputation: 1638

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, i.e. using the async function prefix or the @asyncio.coroutine decorator.

Upvotes: 1

Related Questions