call_soon,即刻执行
import asyncio
def callback(sleep_times):
print('sleep {} success'.format(sleep_times))
def stop_loop(loop):
loop.stop()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.call_soon(callback, 2)
loop.call_soon(stop_loop, loop)
loop.run_forever()
"""
运行结果:
sleep 2 success
Process finished with exit code 0
"""
call_later,指定时间之后再运行,执行的顺序和指定的时间有关,cal_soon比call_later优先执行
import asyncio
def callback(sleep_times):
print('sleep {} success'.format(sleep_times))
def stop_loop(loop):
loop.stop()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.call_later(1, callback, 1)
loop.call_later(2, callback, 2)
loop.call_later(3, callback, 3)
loop.run_forever()
"""
运行结果:
sleep 1 success
sleep 2 success
sleep 3 success
"""
call_at,也是指定时间之后再执行,但是这个时间是loop里面的时间
import asyncio
def callback(sleep_times, loop):
print('sleep {} success, loop time {} '.format(sleep_times, loop.time()))
def stop_loop(loop):
loop.stop()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
now = loop.time()
loop.call_at(now+1, callback, 1, loop)
loop.call_at(now+2, callback, 2, loop)
loop.call_at(now+3, callback, 3, loop)
loop.run_forever()
"""
运行结果:
sleep 1 success, loop time 2861146.171
sleep 2 success, loop time 2861147.171
sleep 3 success, loop time 2861148.171
"""
学习视频