python轮询如何执行某函数
这篇文章主要讲解了python轮询如何执行某函数,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
目标:python中每隔特定时间执行某函数
方法1:使用python的Thread类的子类Timer,该子类可控制指定函数在特定时间后执行一次:
所以为了实现多次定时执行某函数,只需要在一个while循环中多次新建Timer即可。
from threading import Timerimport 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.1897497Hello当前时间戳是 1569224254.1911764Hello当前时间戳是 1569224255.1924803Hello当前时间戳是 1569224256.1957717Hello当前时间戳是 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.5843027Hello当前时间戳是 1569224699.5843854Hello当前时间戳是 1569224700.5870178Hello当前时间戳是 1569224701.5881224Hello当前时间戳是 1569224702.588771Hello当前时间戳是 1569224703.5896Hello当前时间戳是 1569224704.5902……
总结:感觉方法2更节约资源,因为同样使用了while循环,方法2没有生成多余的线程,但是方法1会生成很多的线程
看完上述内容,是不是对python轮询如何执行某函数有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。