【问题标题】:using the python threading.timer to execute the callback function and kill the previous function使用python threading.timer 执行回调函数并杀死前一个函数
【发布时间】:2017-08-16 08:55:37
【问题描述】:

代码如下:

import threading
import time

def fun_01() :
    timer = threading.Timer(3,call_back)

    print("start~")

    timer.start()

    #If the call_back function is executed after 3 seconds,
    # the fun_01 function must be terminated (before 10 seconds have elapsed)
    print("waiting")
    time.sleep(5)
    print("end wait")


    print("Hello~")

    return "exit"

def call_back():
    print("call_back")
    return "end"

print(fun_01())

如果call_back函数在3秒后执行, fun_01 函数必须终止(在 10 秒之前) .......帮帮我

【问题讨论】:

    标签: python multithreading python-3.x function


    【解决方案1】:

    您可以为此使用threading.Event

    import threading
    
    def fun_01():
        # If the event is set then the function immediately exits.
        kill_me = threading.Event()
    
        timer = threading.Timer(3, call_back, [kill_me])
    
        print("start~")
    
        timer.start()
    
        # If the call_back function is executed after 3 seconds,
        # the fun_01 function will be terminated
        print("waiting")
        try:
            # It will return when the event is set in given time otherwise it will 
            # raise TimeoutError
            kill_me.wait(5)
            return "OK"
        except TimeoutError:
            # In this concrete example this shouldn't ever execute
            print("BUMMER...")
        finally:
            print("end wait")
    
        print("Hello~")
    
        return "exit"
    
    def call_back(event):
        event.set()
    
    print(fun_01())
    

    注意:在 Python 3.6.2 中测试

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      相关资源
      最近更新 更多