用Python怎么写定时器

图片[1]-用Python怎么写定时器-uusu优素-乐高,模型,3d打印,编程

用Python怎么写定时器

定时器功能:在设置的多少时间后执行任务,不影响当前任务的执行

推荐学习《Python教程》。

用Python写定时器的方法如下:

1、常用方法:

fromthreadingimportTimer
t=Timer(interval,function,args=None,kwargs=None)
#interval设置的时间(s)
#function要执行的任务
#args,kwargs传入的参数
t.start()#开启定时器
t.cancel()#取消定时器

2、简单示例:

importtime
fromthreadingimportTimer
deftask(name):
print('%sstartstime:%s'%(name,time.ctime()))
t=Timer(3,task,args=('nick',))
t.start()
print('endtime:',time.ctime())#开启定时器后不影响主线程执行,所以先打印
-------------------------------------------------------------------------------
endtime:WedAug721:14:512019
nickstartstime:WedAug721:14:542019

3、验证码示例:60s后验证码失效

importrandom
fromthreadingimportTimer
#定义Code类
classCode:
#初始化时调用缓存
def__init__(self):
self.make_cache()
defmake_cache(self,interval=60):
#先生成一个验证码
self.cache=self.make_code()
print(self.cache)
#开启定时器,60s后重新生成验证码
self.t=Timer(interval,self.make_cache)
self.t.start()

#随机生成4位数验证码
defmake_code(self,n=4):
res=''
foriinrange(n):
s1=str(random.randint(0,9))
s2=chr(random.randint(65,90))
res+=random.choice([s1,s2])
returnres

#验证验证码
defcheck(self):
whileTrue:
code=input('请输入验证码(不区分大小写):').strip()
ifcode.upper()==self.cache:
print('验证码输入正确')
#正确输入验证码后,取消定时器任务
self.t.cancel()
break
obj=Code()
obj.check()
原文来自:https://www.py.cn
© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容