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

前端 未结 1 2050
天命终不由人
天命终不由人 2021-01-27 02:16

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 t

相关标签:
1条回答
  • 2021-01-27 02:41

    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.

    0 讨论(0)
提交回复
热议问题