Python - 在 true 时每 n 秒运行一次函数

Posted

技术标签:

【中文标题】Python - 在 true 时每 n 秒运行一次函数【英文标题】:Python - Run function every n second while true 【发布时间】:2020-07-15 21:09:09 【问题描述】:

我阅读了很多帖子,但找不到其他条件有效的解决方案。 可悲的是,我的循环永远不会停止。似乎它没有重复检查 project.IsInProgress() = True

如果我的语句仍然为真,我想每两秒检查一次,如果它不再为真,我想中断重复并执行打印语句。

我猜问题是它没有每两秒钟运行一次函数。但我不知道如何处理。

check_status = project.IsInProgress()

while check_status:
    print('Render in progress..')
    time.sleep(2)
else: 
    print('Render is finished')

【问题讨论】:

IsInProgress 返回什么?一个布尔值? 是的,该过程返回一个布尔值,似乎将它附加到一个变量导致布尔值不刷新。当我从 API 中获取所有内容时,我分配了很多变量。我现在在一行中运行所有功能。 【参考方案1】:

试试这个:

while project.IsInProgress():
    print('Render in progress..')
    time.sleep(2)
print('Render is finished')

或者,如果您愿意:

check_status = project.IsInProgress()
while check_status:
    print('Render in progress..')
    time.sleep(2)
    check_status = project.IsInProgress()
print('Render is finished')

【讨论】:

我必须将所有功能放在一起才能使其工作。非常感谢。 GetManager().GetProject().IsRenderingInProgress():【参考方案2】:

您的代码仅在代码开头检查一次进行中,如果为真,则循环将永远持续。 为了检查每次迭代的状态,请尝试:

while project.IsInProgress() :
    print('Render in progress..')
    time.sleep(2)
else: 
    print('Render is finished')

【讨论】:

以上是关于Python - 在 true 时每 n 秒运行一次函数的主要内容,如果未能解决你的问题,请参考以下文章

python tornado写的web服务器脚本,运行时每过一会儿都会发出如下警告,这是怎么回事儿? 该如何解决?

我怎样才能让我的 caroutine 每 x 秒运行一次

如何每隔N秒检查一次android中的Internet连接

每 n 秒复制一次

C++:如何检查外部程序是不是正在运行?

Code+ B 汀博尔二分答案