我想用python做一个函数,每5秒运行一次,直到一个变量达到100%

2024-04-20 02:19:22 发布

您现在位置: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。你知道吗


Tags: the函数is时间情况storageoutthis
1条回答
网友
1楼 · 发布于 2024-04-20 02:19:22

When I start the rebuild process it will first finish that and then start the threading

在其他线程中启动重建过程。你知道吗

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()

相关问题 更多 >