简体   繁体   中英

Call an async function periodically?

I have the following function to call s(c) every one second.

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.

async def s(c):

How to update schedule_next_sync for async function? Should run s() synchronously? Or change schedule_next_sync() to an async function?

Once s is async, you could use asyncio.sleep() instead of the lower-level 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)

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