品易云推流 关闭
文章详情页
文章 > Python常见问题 > 用Python怎么写定时器

用Python怎么写定时器

头像

月亮邮递员

2020-04-03 13:00:323575浏览 · 0收藏 · 0评论

用Python怎么写定时器

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

推荐学习《Python教程》。

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

1、常用方法:

from threading import Timer
t = Timer(interval, function, args=None, kwargs=None)
# interval 设置的时间(s) 
# function 要执行的任务
# args,kwargs 传入的参数

t.start()  # 开启定时器
t.cancel()  # 取消定时器

2、简单示例:

import time
from threading import Timer

def task(name):
    print('%s starts time: %s'%(name, time.ctime()))

t = Timer(3,task,args=('nick',))
t.start()
print('end time:',time.ctime())  # 开启定时器后不影响主线程执行,所以先打印

-------------------------------------------------------------------------------
end time: Wed Aug  7 21:14:51 2019
nick starts time: Wed Aug  7 21:14:54 2019

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

import random
from threading import Timer

# 定义Code类
class Code:
    # 初始化时调用缓存
    def __init__(self):
        self.make_cache()

    def make_cache(self, interval=60):
        # 先生成一个验证码
        self.cache = self.make_code()
        print(self.cache)
        # 开启定时器,60s后重新生成验证码
        self.t = Timer(interval, self.make_cache)
        self.t.start()
    
    # 随机生成4位数验证码
    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:
            code = input('请输入验证码(不区分大小写):').strip()
            if code.upper() == self.cache:
                print('验证码输入正确')
                # 正确输入验证码后,取消定时器任务
                self.t.cancel()
                break

obj = Code()
obj.check()

Python中文网,大量Python视频教程,欢迎学习!

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图