• 【12.3】call_soon、call_at、call_later、call_soon_threadsafe


    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 
    
  • 相关阅读:
    OC语言前期准备
    C语言指针
    C语言字符串
    C语言数组
    python语法
    shell脚本命令 运行python文件&python命令行运行python代码
    HTTP Status完整枚举
    CRON表达式
    mybatis-generator生成的mapper中的
    iOS事件的响应和传递机制
  • 原文地址:https://www.cnblogs.com/zydeboke/p/11372463.html
Copyright © 2020-2023  润新知