[英]Call an async function periodically?
I have the following function to call s(c)
every one second.我有以下 function 每隔一秒调用一次
s(c)
。
def schedule_next_sync():
t = datetime.datetime.now() + datetime.timedelta(seconds=1)
def wrapper():
s(c)
schedule_next_sync()
tornado.ioloop.IOLoop.current().add_timeout(datetime.datetime.timestamp(t), wrapper)
However, s()
will be changed to an async function.但是,
s()
将更改为异步 function。
async def s(c):
How to update schedule_next_sync
for async function?如何更新异步 function 的
schedule_next_sync
? Should run s()
synchronously?应该同步运行
s()
吗? Or change schedule_next_sync()
to an async function?或者将
schedule_next_sync()
更改为异步 function?
Once s
is async, you could use asyncio.sleep()
instead of the lower-level add_timeout()
:一旦
s
是异步的,您就可以使用asyncio.sleep()
而不是较低级别的add_timeout()
:
async def schedule_next_sync():
async def call_forever():
while True:
await asyncio.sleep(1)
await s(c)
tornado.ioloop.IOLoop.current().create_task(call_forever())
If you really want to do it with timeouts, something like this should work:如果你真的想用超时来做,这样的事情应该可以工作:
def schedule_next_sync():
t = datetime.datetime.now() + datetime.timedelta(seconds=1)
def wrapper():
loop = asyncio.get_running_loop()
task = loop.create_task(s(c))
task.add_done_callback(lambda _: schedule_next_sync())
loop = tornado.ioloop.IOLoop.current()
loop.add_timeout(datetime.datetime.timestamp(t), wrapper)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.