以下是代码:
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秒之前) .......帮助我
答案 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中测试