python asyncio call_soon, call_at, call_later

时间:2021-02-01 21:02:04

1. call_soon, 协程一运行就马上运行

def callback(sleep_times):
    print("success time {}".format(sleep_times))#call_later, call_at
if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.call_soon(callback, 4)
    loop.stop() # 要写这个,不然不会停止
    loop.run_forever()

 

 

2. call_later

import asyncio

def callback(sleep_times):
    print("success time {}".format(sleep_times))

#call_later, call_at
if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    now = loop.time()
    loop.call_later(2, callback, 2)
    loop.call_later(1, callback, 1)
    loop.call_later(3, callback, 3)
    loop.call_soon(callback, 4) # call_soon 快于call_later
    loop.run_forever()

 

 

3. call_at

import asyncio

def callback(loop, i):
    print("success time {} {}".format(i, loop.time()))

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    now = loop.time()
    loop.call_at(now+2, callback, loop, 2) # 指定时间运行, 时间是协程内部的时间
    loop.call_at(now+1, callback, loop, 1)
    loop.call_at(now+3, callback, loop, 3)
    loop.call_soon(callback, loop, 4)
    loop.run_forever()