使用python threading.timer执行回调函数并终止前一个函数

时间:2017-08-16 08:55:37

标签: python multithreading python-3.x function

以下是代码:

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())

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

1 个答案:

答案 0 :(得分:0)

您可以使用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中测试