python中的定时器threading.Timer

python开发中用到,定时操作。例如每隔1s执行一次,发现  threading.Timer,这个东西,可以直接用。

其原理为执行函数中置定时函数Timer(),递归调用自己,看来实现方法比较拙劣。

import threading
import time

def fun_timer():
    print("hello timer!")
    # 定义全局变量
    global timer1
    # 1秒调用函数一次
    timer1 = threading.Timer(1, fun_timer)
    # 启用定时器
    timer1.start()


fun_timer()

time.sleep(10)

timer1.cancel() #取消执行
结果 :
/usr/local/bin/python3  ThreadingTimer.py
hello timer!
hello timer!
hello timer!
hello timer!
hello timer!
hello timer!
hello timer!
hello timer!
hello timer!
hello timer!

Process finished with exit code 0
原文地址:https://www.cnblogs.com/sdadx/p/6710262.html