Python定时器
定义:
# 此类表示一个操作应该在等待一定的时间之后运行 --- 相当于一个定时器。 Timer 类是 Thread 类的子类,因此可以像一个自定义线程一样工作。
用法:
# 与线程一样,通过调用 start() 方法启动定时器。
# 而 cancel() 方法可以停止计时器(在计时结束前), 定时器在执行其操作之前等待的时间间隔可能与用户指定的时间间隔不完全相同。
部分尝试:
timerPrint.py
import time
import threading
def timeCount():
while 1:
localtime = time.asctime(time.localtime(time.time()))
print("时间为 :", localtime)
time.sleep(1)
def hello():
timeCount()
t1 = threading.Timer(2, hello) # recursive call function -> hello
t1.start()
main.py
from timerPrint import hello
import threading
def date_p():
t = threading.Timer(2, hello)
t.start() # after 2 seconds, date will be printed
if __name__ == '__main__':
date_p()