python_loop_break

python_loop_break

本文总结python 语言定时跳出循环的方案,主要分为两种情况:

  • 循环中无阻塞的可能
    这种情况比较简单,可以直接用时间差的判断是否跳出即可:
    1
    2
    3
    4
    5
    import time

    t_end = time.time() + 60 * 15
    while time.time() < t_end:
    # do whatever you do但是必须保证不存在阻塞的可能
  • 循环中可能会发生阻塞
    这种就比较复杂,因为可能循环会阻塞在特定的语句,所以无法用上面的方法来实现,
    必须要另开一线程来使循环线程和计时判断线程同时进行,这样就不会有阻碍了。下面的
    代码是我查资料采取的方案:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    from multiprocessing import Process
    import time


    def task(msg):
    while 1:
    print ('hello, %s' % msg)
    time.sleep(1)
    pass



    if __name__ == '__main__':
    p = Process(target=task, args=('world',))

    p.start()
    p.join(0.15)
    if p.is_alive():
    print('Process: %s is running' % p.pid)
    p.terminate()

尽管这个task中的循环不包括阻塞的可能,但是这段代码是可以完全应对发生阻塞的情况。

# Python

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×