call_soon,即刻执行
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import asyncio 4 5 6 def callback(sleep_times): 7 print('sleep {} success'.format(sleep_times)) 8 9 10 def stop_loop(loop): 11 loop.stop() 12 13 14 if __name__ == '__main__': 15 loop = asyncio.get_event_loop() 16 # 即刻执行 17 loop.call_soon(callback, 2) 18 loop.call_soon(stop_loop, loop) 19 loop.run_forever()
sleep 2 success Process finished with exit code 0
call_later,指定时间之后再运行,执行的顺序和指定的时间有关,cal_soon比call_later优先执行
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import asyncio 4 5 6 def callback(sleep_times): 7 print('sleep {} success'.format(sleep_times)) 8 9 10 def stop_loop(loop): 11 loop.stop() 12 13 14 if __name__ == '__main__': 15 loop = asyncio.get_event_loop() 16 # 指定时间之后再运行 17 loop.call_later(1, callback, 1) 18 loop.call_later(2, callback, 2) 19 loop.call_later(3, callback, 3) 20 # loop.call_soon(stop_loop, loop) 21 loop.run_forever()
sleep 1 success sleep 2 success sleep 3 success
call_at,也是指定时间之后再执行,但是这个时间时loop里面的时间
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import asyncio 4 5 6 def callback(sleep_times, loop): 7 print('sleep {} success, loop time {} '.format(sleep_times, loop.time())) 8 9 10 def stop_loop(loop): 11 loop.stop() 12 13 14 if __name__ == '__main__': 15 loop = asyncio.get_event_loop() 16 now = loop.time() 17 # 指定时间之后再运行 18 loop.call_at(now+1, callback, 1, loop) 19 loop.call_at(now+2, callback, 2, loop) 20 loop.call_at(now+3, callback, 3, loop) 21 # loop.call_soon(stop_loop, loop) 22 loop.run_forever()
sleep 1 success, loop time 2861146.171 sleep 2 success, loop time 2861147.171 sleep 3 success, loop time 2861148.171