threading.Timer 使用基本清理控制杀死长时间运行的任务 [英] threading.Timer to kill long running task with basic cleanup control

查看:36
本文介绍了threading.Timer 使用基本清理控制杀死长时间运行的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to monitor a process and auto-kill it if it runs more than N seconds.

我正在编辑这个问题,以回应以下建议:有没有办法在 Python 中杀死线程?

I'm editing this question in response to the suggestion that it's a duplicate of: Is there any way to kill a Thread in Python?

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

I'd argue that my question is slightly different in that I'm focused on basic cleanup AFTER thread completion (which might actually be more difficult than the aforementioned possible duplicate as everyone seems to say it's impossible).

作为一个简单的测试,我正在尝试以下操作以尝试在 2 秒后终止该进程:

As a simple test, I'm attempting the following to try and kill the process after 2 seconds:

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)

推荐答案

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

So... I think may have solved this by combining 10 different SO posts in a way that I've not seen on any single SO post... please critique and tell me if this is dumb or brilliant... ;-)

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

[Because this question is very closely related to at least two others... I've posted my proposed solution as an independent answer in the both related threads: 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]

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

I think that's the secret sauce that will work for my application. My sub-thread is cleaned up properly now after a fixed amount of time with no looping flag check nonsense within said sub-thread... AND I appear to even get a small glimmer of control in the subthread where I can do some final state checking and cleanup.

这篇关于threading.Timer 使用基本清理控制杀死长时间运行的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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