我想在python中创建一个每5秒运行一次的函数,直到变量达到100%

时间:2012-10-03 11:07:41

标签: python

所以我想创建一个函数来打印重建的进度和完成此重建的剩余时间。但是一旦重建达到100%,它就需要结束。这就是我到目前为止所做的:

def progress():
    # This prints out the time left until rebuild is done.
    loudEchoCMD("storage::rebuild-eta")
    # This prints out the % of the rebuild that is done.
    rebuildProgress = loudEchoCMD("storage::rebuild-progress") 
    print rebuildProgress 
    if rebuildProgress != '100%':
        global t 
        t = threading.Timer(5.0, progress)
        t.start()
    else:
        t.cancel()

当我开始重建过程时,它将首先完成该过程,然后启动线程,而不是让线程每隔五秒打印出进度和ETA。

1 个答案:

答案 0 :(得分:2)

  

当我开始重建过程时,它将首先完成该过程   开始线程

在另一个主题中开始重建过程。

import threading
build = threading.Thread(target = start_rebuild)
build.start()
progress()
build.join()  # wait for build thread to end

另外,假设progress完成时间不到5秒,我认为省略global tt.cancel就足够了:

def progress():
    # This prints out the time left until rebuild is done.
    loudEchoCMD("storage::rebuild-eta")
    # This prints out the % of the rebuild that is done.
    rebuildProgress = loudEchoCMD("storage::rebuild-progress") 
    print rebuildProgress 
    if rebuildProgress != '100%':
        t = threading.Timer(5.0, progress)
        t.start()