5
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

4 回答 4

13

从文档中:

类 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)
于 2012-06-20T17:23:59.253 回答
1

文档

class threading.Timer( interval , function , args =[], kwargs ={})¶ 创建一个计时器,该计时器将在间隔秒数过去后使用参数args和关键字参数kwargs运行函数。

我找不到关于反复调用某事的任何信息。也许其他人有更好的答案,或者您可能必须手动滚动它(这不会太难)。

于 2012-06-20T17:20:32.593 回答
0

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

于 2012-06-20T17:22:30.767 回答
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 分钟后,我使用此代码

于 2016-12-27T16:58:37.383 回答