我正在使用此代碼doSomething每 3 秒調用一次函數。但我想要那個時候numeroPeticiones== 3,停止這樣做。我找了很多例子,但沒有一個有效。就我而言,即使numeroPeticiones== 3滿足的條件,我的函數仍將永遠執行。我該如何解決?import threadingfrom threading import TimernumeroPeticiones=0def doSomething(): global numeroPeticiones numeroPeticiones=numeroPeticiones+1 print ("hello, world",numeroPeticiones) if numeroPeticiones == 3: print("cancel") t.cancel()def set_interval(func, sec): def func_wrapper(): set_interval(func, sec) func() t = threading.Timer(sec, func_wrapper) t.start() return t
1 回答

明月笑刀無情
TA貢獻1828條經驗 獲得超4個贊
您可以執行以下操作,如果 num 等于 3,則不會啟動計時器
from threading import Timer
num = 0
def hello():
global num
num += 1
print("hello, world")
if (num < 3):
Timer(3, hello).start()
Timer(3, hello).start()
添加回答
舉報
0/150
提交
取消