threading.Timer to kill long running task with basic cleanup control

不想你离开。 提交于 2019-12-31 04:25:13

问题


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

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).

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)

回答1:


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... ;-)

[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()

Yields:

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.



来源:https://stackoverflow.com/questions/50473309/threading-timer-to-kill-long-running-task-with-basic-cleanup-control

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!