时间段后停止代码 [英] Stop code after time period

查看:59
本文介绍了时间段后停止代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用 foo(n) 但如果它运行超过 10 秒就停止它.这样做的好方法是什么?

I would like to call foo(n) but stop it if it runs for more than 10 seconds. What's a good way to do this?

我可以看到理论上我可以修改 foo 本身以定期检查它已经运行了多长时间,但我不想这样做.

I can see that I could in theory modify foo itself to periodically check how long it has been running for but I would prefer not to do that.

推荐答案

给你:

import multiprocessing
import time

# Your foo function
def foo(n):
    for i in range(10000 * n):
        print "Tick"
        time.sleep(1)

if __name__ == '__main__':
    # Start foo as a process
    p = multiprocessing.Process(target=foo, name="Foo", args=(10,))
    p.start()

    # Wait 10 seconds for foo
    time.sleep(10)

    # Terminate foo
    p.terminate()

    # Cleanup
    p.join()

这将等待 foo 10 秒然后杀死它.

This will wait 10 seconds for foo and then kill it.

更新

仅在进程正在运行时终止进程.

Terminate the process only if it is running.

# If thread is active
if p.is_alive():
    print "foo is running... let's kill it..."

    # Terminate foo
    p.terminate()

更新 2:推荐

使用 jointimeout.如果 foo 在超时之前完成,那么 main 可以继续.

Use join with timeout. If foo finishes before timeout, then main can continue.

# Wait a maximum of 10 seconds for foo
# Usage: join([timeout in seconds])
p.join(10)

# If thread is active
if p.is_alive():
    print "foo is running... let's kill it..."

    # Terminate foo
    p.terminate()
    p.join()

这篇关于时间段后停止代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆