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会生成很多的线程

发布了63 篇原创文章 · 获赞 18 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/liuxiang15/article/details/98063647