• 技术文章 >常见问题 >Python常见问题

    用Python怎么写定时器

    月亮邮递员月亮邮递员2020-04-03 13:00:32原创3607

    用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视频教程,欢迎学习!

    专题推荐:python 定时器 写法
    品易云
    上一篇:怎么调Python的黑框样式 下一篇:什么叫Python运算符重载

    相关文章推荐

    • Python中的简单定时器• Python Timer定时器:控制函数在特定时间执行

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网