[英]How to run async function forever (Python)
How do I use asyncio and run the function forever. 如何使用asyncio并永久运行该功能。 I know that there's
run_until_complete(function_name)
but how do I use run_forever
how do I call the async function? 我知道这里有
run_until_complete(function_name)
但是如何使用run_forever
如何调用异步函数?
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()
. run_forever
并不意味着异步函数将永远运行,这意味着循环将永远运行,或者至少直到有人调用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. 这就是为什么
run_forever()
不接受参数,也不在乎任何特定的协程。 The typical pattern is to add some coroutines using loop.create_task
or equivalent before invoking run_forever()
. 典型的模式是在调用
run_forever()
之前使用loop.create_task
或等效方法添加一些协程。 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. 但是,即使一个不执行任何任务并
asyncio.run_coroutine_threadsafe
的事件循环也可能很有用,因为另一个线程可以调用asyncio.run_coroutine_threadsafe
并使其正常工作。
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: 如果您希望在初始化循环之前向循环添加函数,那么
loop.run_forever()
之前的以下行就足够了:
asyncio.async(function())
To add a function to a loop that is already running you'll need ensure_future
: 要将功能添加到已在运行的循环中,您将需要
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. 在这两种情况下,都必须以某种方式将要调用的函数指定为异步函数,即使用
async
函数前缀或@asyncio.coroutine
装饰器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.