温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python轮询如何执行某函数

发布时间:2020-07-29 09:40:09 来源:亿速云 阅读:116 作者:小猪 栏目:开发技术

这篇文章主要讲解了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轮询如何执行某函数有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI