Python线程.Timer只重复一次

Sha*_*mar 4 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()
    .
    .
    .
Run Code Online (Sandbox Code Playgroud)

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

Ult*_*nct 13

从文档:

class threading.Timer

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

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

def ExecuteDemo():
    .
    .
    .
    threading.Timer(2, ExecuteDemo).start()
Run Code Online (Sandbox Code Playgroud)

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

我会建议这样的事情:

def ExecuteDemoCaller():
    #while True: # or something..
    while someCondition:
        ExecuteDemo()
        time.sleep(2)
Run Code Online (Sandbox Code Playgroud)