学习编程就像学习骑自行车一样,对新手来说最重要的是持之以恒的练习。
在《汲取地下水》这一章节中看见的一句话:“别担心自己的才华或能力不足。持之以恒地练习,才华便会有所增长”,现在想来,真是如此。
一、timer类介绍
Timer(定时器)是Thread的派生类,用于在指定时间后调用一个方法。
二、timer语法
Timer(interval, function, args=[], kwargs={})
- interval: 指定的时间
- function: 要执行的方法
- args/kwargs: 方法的参数
三、简易定时器实例
from threading import Timer
def hello(name):
print("%s hello, world" % name)
t = Timer(2, hello, args=('金鞍少年',)) # 第一个参数指定的时 时间,第二个是运行函数名
t.start() # after 2 seconds, "金鞍少年 hello, world" will be printed
四、Timer类的cancel()方法
Timer.cancel()
主要作用:是清除任务队列中的任务, 在 Timer中可以用它实现定时任务执行过程中的中止 。
五、timer在web中应用实例
模拟注册发送验证码
from threading import Timer
import random, time
class Code:
def __init__(self):
self.make_cache()
# 定时打印验证码
def make_cache(self, interval=5):
self.cache = self.make_code()
print(self.cache)
self.t = Timer(interval, self.make_cache) # 定时5秒,触发 make_cache 函数 ,打印验证码
self.t.start()
# 生成随机验证码
def make_code(self, n=4):
res = ''
for i in range(n):
s1 = str(random.randint(0, 9)) # 数字
s2 = chr(random.randint(65, 90)) # 大写字母
res += random.choice([s1, s2])
return res # 返回四位数验证码
# 判断验证码
def check(self):
while True:
inp = input('>>: ').strip()
if inp.upper() == self.cache:
print('验证成功', end='\n')
self.t.cancel() # 停止定时器
break
if __name__ == '__main__':
obj = Code()
obj.check()