Python线程.Timer只重复一次

时间:2012-06-20 17:09:14

标签: python multithreading

def On_Instrumentation_StartAnimation():  

    """
    Syntax      : On_Instrumentation_StartAnimation()
    Purpose     : Fired if the animation is started
    Parameters  : None
    """
    print "----------------------------------------------------------------------------------------"
    localtime = time.asctime(time.localtime(time.time()))
    global start
    start = time.clock()
    print "The user entered Animation Mode at local time: ", localtime
    print("This data has also been written to 'c:\dSPACE71\cdlog\cdlog.txt'")   
    threading.Timer(2, ExecuteDemo).start()
    ExecuteDemo()
    # Printing to the text file
    file1 = open('c:\dSPACE71\cdlog\cdlog.txt', 'a')
    file1.write("\n----------------------------------------------------------------------------------------")
    file1.write("\nThe user entered Animation Mode at local time: ")
    file1.write(localtime)
    file1.close()      

def ExecuteDemo()
    .
    .
    .
    Current_value = Current.Read()
    localtime = time.asctime(time.localtime(time.time()))
    print "The current reading at localtime:", localtime, "is", str(Current_value) + "."
    # Printing to the text file
    file1 = open('c:\dSPACE71\cdlog\cdlog.txt', 'a')
    file1.write("\n----------------------------------------------------------------------------------------")
    file1.write("\nThe current reading at localtime: ")
    file1.write(localtime)
    file1.write(" is: ")
    file1.write(str(Current_value))
    file1.close()
    .
    .
    .

正如您所希望看到的那样,我试图在调用StartAnimation函数后每2秒重复一次ExecuteDemo()函数。但我的问题是我的ExecuteDemo()只运行两次。我怎么能让它继续重复?我错过了什么吗?

4 个答案:

答案 0 :(得分:12)

来自文档:

  

class threading.Timer

     

在指定的时间间隔过后执行函数的线程。

这意味着Threading.Timer会在指定的时间段后调用函数。正如你所注意到的那样,它只被调用一次。这里的解决方案是在ExecuteDemo(..)函数结束时再次设置计时器。

def ExecuteDemo():
    .
    .
    .
    threading.Timer(2, ExecuteDemo).start()

在我看来,上述方法效率不高。就像每2秒创建一个新线程一样,一旦执行该函数,它就会在创建下一个线程之前消失。

我会建议这样的事情:

def ExecuteDemoCaller():
    #while True: # or something..
    while someCondition:
        ExecuteDemo()
        time.sleep(2)

答案 1 :(得分:1)

来自docs

  

类threading.Timer( interval function args = [], kwargs = {}) ¶   使用参数 args 和关键字创建一个运行 function 的计时器   在 interval 秒后,参数 kwargs

我找不到任何关于反复调用的东西。也许其他人有更好的答案,或者你可能需要手动操作(这不会太难)。

答案 2 :(得分:0)

计时器不重复。您可以在回调函数结束时设置另一个计时器。

答案 3 :(得分:0)

class setInterval(threading.Thread):
 def __init__(self, interval, function, args=[], kwargs={}):
  threading.Thread.__init__(self)
  self.interval = interval
  self.function = function
  self.args = args
  self.kwargs = kwargs
  self.finished = threading.Event()
  self.flag_run = True
 def cancel(self):
  self.finished.set()
 def run(self):
  while self.flag_run:
   self.finished.wait(self.interval)
   if not self.finished.is_set(): self.function(*self.args, **self.kwargs)
   else: self.flag_run = False
  self.finished.set()

读完" threading.py" 10分钟后我用这个代码