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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值