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

 

相关文章:

  • 2022-12-23
  • 2021-06-14
  • 2021-05-20
  • 2021-08-14
  • 2021-06-26
  • 2022-01-18
  • 2022-03-07
猜你喜欢
  • 2022-12-23
  • 2023-01-18
  • 2022-12-23
  • 2022-12-23
  • 2021-08-16
  • 2021-06-18
相关资源
相似解决方案