首页 > 解决方案 > threading.Timer 用基本的清理控制杀死长时间运行的任务

问题描述

我想监视一个进程并在它运行超过 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)

标签: pythontimeout

解决方案


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

[因为这个问题与至少其他两个问题密切相关......我已经在两个相关线程中发布了我提出的解决方案作为独立答案:1 2 ]

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]

我认为这是适用于我的应用程序的秘诀。我的子线程现在在固定的时间后被正确清理,在所述子线程中没有循环标志检查废话......而且我似乎什至在子线程中获得了一点控制,我可以做一些最终状态检查和清理。


推荐阅读