python轮询如何执行某函数
更新:HHH   时间:2023-1-7


这篇文章主要讲解了python轮询如何执行某函数,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

目标:python中每隔特定时间执行某函数

方法1:使用python的Thread类的子类Timer,该子类可控制指定函数在特定时间后执行一次:

所以为了实现多次定时执行某函数,只需要在一个while循环中多次新建Timer即可。

from threading import Timer
import time
 
def printHello():
 print ("Hello")
 print("当前时间戳是", time.time())
 
def loop_func(func, second):
 #每隔second秒执行func函数
 while True:
  timer = Timer(second, func)
  timer.start()
  timer.join()
 
loop_func(printHello, 1)

运行结果如下:

Hello
当前时间戳是 1569224253.1897497
Hello
当前时间戳是 1569224254.1911764
Hello
当前时间戳是 1569224255.1924803
Hello
当前时间戳是 1569224256.1957717
Hello
当前时间戳是 1569224257.1964536
……

方法2:使用time模块的sleep函数可以阻塞程序执行

import time
 
def printHello():
 print ("Hello")
 print("当前时间戳是", time.time())
 
def loop_func(func, second):
 # 每隔second秒执行func函数
 while True:
  func()
  time.sleep(second)
 
loop_func(printHello, 1)

运行结果如下:

Hello
当前时间戳是 1569224698.5843027
Hello
当前时间戳是 1569224699.5843854
Hello
当前时间戳是 1569224700.5870178
Hello
当前时间戳是 1569224701.5881224
Hello
当前时间戳是 1569224702.588771
Hello
当前时间戳是 1569224703.5896
Hello
当前时间戳是 1569224704.5902
……

总结:感觉方法2更节约资源,因为同样使用了while循环,方法2没有生成多余的线程,但是方法1会生成很多的线程

看完上述内容,是不是对python轮询如何执行某函数有进一步的了解,如果还想学习更多内容,欢迎关注天达云行业资讯频道。

返回开发技术教程...