首先想要實現的效果是:每隔1段時間,就去調用1個接口確認結果,直到接口返回的結果為true,停止調用
所以這里會用到python的定時器
先來了解最簡單的定時器:
python 定時器默認定時器只執行一次,第一個參數單位S,幾秒后執行
import threading def fun_timer(): print('Hello Time') timer = threading.Timer(1,fun_timer) #停留1s再去調用 fun_timer
timer.start()
改成以下可以執行多次
建立loopTime.py
1 from threading import Timer 2
3 def fun_timer(): 4 print('Hello Timer!') 5
6 class LoopTimer(Timer): 7 """Call a function after a specified number of seconds: 8 t = LoopTi 9 mer(30.0, f, args=[], kwargs={}) 10 t.start() 11 t.cancel() # stop the timer's action if it's still waiting 12 """
13
14
15 def __init__(self,interval,function,args=[],kwargs={}): 16 Timer.__init__(self,interval,function,args,kwargs) 17
18 def run(self): 19 '''self.finished.wait(self.interval) 20 if not self.finished.is_set(): 21 self.function(*self.args, **self.kwargs) 22 self.finished.set()'''
23
24 while True: 25 self.finished.wait(self.interval) 26 if self.finished.is_set(): 27 self.finished.set() 28 break
29 self.function(*self.args,**self.kwargs) 30
31 t = LoopTimer(120,fun_timer) 32 t.start()
這個程序的運行結果是:每隔120秒,調用1次fun_timer(即打印一次Hello Timer)
參考博客:
https://blog.csdn.net/u013378306/article/details/79024432
