优草派  >   Python

用Python怎么写定时器?这篇文章通过源码来教会你

陈立鑫            来源:优草派

很多小伙伴想看如何使用python写定时器?今天它来了!小编就通过这篇文文章来给大家分享一个实现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写定时器的方法,希望大家通过阅读小编的文章之后能够有所收获!如果大家觉得小编的文章不错的话,可以多多分享给有需要的人。

【原创声明】凡注明“来源:优草派”的文章,系本站原创,任何单位或个人未经本站书面授权不得转载、链接、转贴或以其他方式复制发表。否则,本站将依法追究其法律责任。
TOP 10
  • 周排行
  • 月排行