首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python threading.timer -每'n‘秒重复一次函数

Python threading.timer -每'n‘秒重复一次函数
EN

Stack Overflow用户
提问于 2012-09-15 14:49:12
回答 11查看 249.8K关注 0票数 114

我希望每隔0.5秒启动一个函数,并能够启动、停止和重置计时器。我不太了解Python线程是如何工作的,并且在使用python计时器时遇到了困难。

然而,当我执行两次threading.timer.start()时,我仍然得到RuntimeError: threads can only be started once。有没有解决这个问题的办法?我尝试在每次启动之前应用threading.timer.cancel()

伪代码:

代码语言:javascript
复制
t=threading.timer(0.5,function)
while True:
    t.cancel()
    t.start()
EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2012-09-15 14:56:41

最好的方法是启动计时器线程一次。在您的计时器线程中,您将编写以下代码

代码语言:javascript
复制
class MyThread(Thread):
    def __init__(self, event):
        Thread.__init__(self)
        self.stopped = event

    def run(self):
        while not self.stopped.wait(0.5):
            print("my thread")
            # call a function

在启动计时器的代码中,然后可以set停止事件以停止计时器。

代码语言:javascript
复制
stopFlag = Event()
thread = MyThread(stopFlag)
thread.start()
# this will stop the timer
stopFlag.set()
票数 130
EN

Stack Overflow用户

发布于 2013-05-04 06:40:03

来自Equivalent of setInterval in python

代码语言:javascript
复制
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

用法:

代码语言:javascript
复制
@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() 

或者这是the same functionality but as a standalone function instead of a decorator

代码语言:javascript
复制
cancel_future_calls = call_repeatedly(60, print, "Hello, World")
# ...
cancel_future_calls() 

Here's how to do it without using threads

票数 37
EN

Stack Overflow用户

发布于 2014-06-30 18:29:32

使用计时器线程-

代码语言:javascript
复制
from threading import Timer,Thread,Event


class perpetualTimer():

   def __init__(self,t,hFunction):
      self.t=t
      self.hFunction = hFunction
      self.thread = Timer(self.t,self.handle_function)

   def handle_function(self):
      self.hFunction()
      self.thread = Timer(self.t,self.handle_function)
      self.thread.start()

   def start(self):
      self.thread.start()

   def cancel(self):
      self.thread.cancel()

def printer():
    print 'ipsem lorem'

t = perpetualTimer(5,printer)
t.start()

这可以由t.cancel()停止

票数 32
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12435211

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档