python 定时器,轮询定时器
首先想要实现的效果是:每隔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