threading.Timer使用基本清理控制来终止长时间运行的任务

时间:2018-05-22 17:20:55

标签: python timeout

我想监视一个进程并在运行超过N秒时自动终止它。

我正在编辑这个问题,以回应它的重复: Is there any way to kill a Thread in Python?

我认为我的问题略有不同,因为我专注于线程完成后的基本清理(实际上可能比上述可能的重复更困难,因为每个人似乎都认为这是不可能的。)

作为一个简单的测试,我尝试以下尝试在2秒后尝试杀死该过程:

import threading
import sys
import time

def after_timeout():
  print "KILL THE WORLD HERE!"
  # whats the secret sauce here (if any)?
  # sys.exit() and other variants aren't
  # killing the main thread... is it possible?

threading.Timer(2, after_timeout).start()

i = 0
while True:
  print i
  i += 1
  time.sleep(1)

1 个答案:

答案 0 :(得分:0)

所以...我认为可能通过在任何单个SO帖子上都没有看到的方式组合10个不同的SO帖子来解决这个问题...请批评并告诉我这是愚蠢还是辉煌。 ..; - )

[因为这个问题与至少其他两个问题密切相关......我已将我提出的解决方案作为独立答案发布在两个相关主题中:the MS documentation page 1] < / p>

import threading
import time
import atexit

def do_work():

  i = 0
  @atexit.register
  def goodbye():
    print ("'CLEANLY' kill sub-thread with value: %s [THREAD: %s]" %
           (i, threading.currentThread().ident))

  while True:
    print i
    i += 1
    time.sleep(1)

t = threading.Thread(target=do_work)
t.daemon = True
t.start()

def after_timeout():
  print "KILL MAIN THREAD: %s" % threading.currentThread().ident
  raise SystemExit

threading.Timer(2, after_timeout).start()

收率:

0
1
KILL MAIN THREAD: 140013208254208
'CLEANLY' kill sub-thread with value: 2 [THREAD: 140013674317568]

我认为这对我的申请有用。在一段固定的时间后,我的子线程被正确清理,没有循环标志,检查所述子线程中的无意义...并且我似乎甚至在子线程中获得一小部分控制,我可以做一些最终状态检查和清理。