当前位置: 移动技术网 > IT编程>脚本编程>Python > python 轮询执行某函数的2种方式

python 轮询执行某函数的2种方式

2020年05月12日  | 移动技术网IT编程  | 我要评论

云企招聘,大连被奷杀解剖女尸,邹锡昌

目标: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 轮询执行某函数的2种方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网