python定时器5秒执行一次_Python threading.timer-每隔“n”秒重复一次函数

import threading

def setInterval(interval):

def decorator(function):

def wrapper(*args, **kwargs):

stopped = threading.Event()

def loop(): # executed in another thread

while not stopped.wait(interval): # until stopped

function(*args, **kwargs)

t = threading.Thread(target=loop)

t.daemon = True # stop if the program exits

t.start()

return stopped

return wrapper

return decorator

用法:@setInterval(.5)

def function():

"..."

stop = function() # start timer, the first call is in .5 seconds

stop.set() # stop the loop

stop = function() # start new timer

# ...

stop.set()cancel_future_calls = call_repeatedly(60, print, "Hello, World")

# ...

cancel_future_calls()

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Python中实现每隔5执行一次函数,可以使用Thread类的子类Timer,该子类允许控制指定函数在特定时间后执行一次。以下是一种实现方法:使用while循环和Timer类来实现每隔5执行一次函数。 ```python from threading import Timer def func(): # 这里写需要执行函数代码 print("执行函数") # 每隔5执行一次func函数 while True: timer = Timer(5, func) timer.start() timer.join() ``` 在上述代码中,我们定义了一个函数`func()`,您可以在其中编写需要执行的代码。然后,使用while循环创建一个Timer对象,设置定时时间为5,将函数`func`传递给Timer对象,然后启动Timer并等待其完成。 请注意,上述代码中的while循环将导致函数`func()`无限循环执行,如果需要在特定条件下停止循环,请根据实际情况修改代码。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [python 轮询执行函数的2种方式](https://download.csdn.net/download/weixin_38738977/14851459)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [python定时器5执行一次_(五)实践出真知——Python定时器、线程、动画制作Animation类](https://blog.csdn.net/weixin_39836751/article/details/110403577)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值