并发编程之定时器

定时器

定时器,指定n秒后执行某操作

简易版:

from threading import Timer


def task(name):
    print('hello %s' % name)


t = Timer(5, task, args=('xiao',))
t.start()

# hello xiao

应用版:

## 验证码定时器
from threading import Timer
import random


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)
        self.t.start()

    def make_code(self, n=4):
        code = ''
        for i in range(n):
            code_list = [random.randint(0, 9),
                         chr(random.randint(65, 90)),
                         chr(random.randint(97, 122))
                         ]
            code += str(random.choice(code_list))
        return code

    def check(self):
        while True:
            code_input = input('请输入你的验证码:').strip()
            if code_input.upper() == self.cache.upper():
                print('验证成功')
                self.t.cancel()
                break


if __name__ == '__main__':
    obj = Code()
    obj.check()

posted @ 2024-03-03 11:30  Xiao0101  阅读(17)  评论(0)    收藏  举报