简体   繁体   中英

Terminating a python thread from within based on a timer

I have tried to solve this problem through multiple forums and still have not got a solution to the answer. I'll try to be as specific as possible as to what I am looking for. I have a use case where I need to have a thread terminate itself after a certain time out. I do not want to use .join(timeout=x) from the main thread because that as I understand does not terminate the thread. I want this timed event to be realized within the thread and it should do some clean up and updates before it terminates itself. JFYI: I can't use a loop wothin the run method to check for a state. My need is that the target function will be called within the run method.

class MyThread(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.timer = Timer(5.0, self.timeout)

    def run(self):
        self.timer.start()
        # call the target function which runs

     def timeout(self):
          # timeout code
          # If timeout has been reached then thread should do some internal cleanup and terminate thread here.

Here is another way using eventlet.timeout . The target_function below is the main logic in the Thread.run block. When time is up, it throws a pre-defined exception. You can add your internal cleanup logic block in the cleanup function.

from eventlet.timeout import Timeout
from eventlet import sleep


class TimeoutError(Exception):
    pass


def target_function(seconds=10):
    print("Run target functions ...")
    for i in range(seconds, -1, -1):
        print("Count down: " + str(i))
        sleep(1)


def cleanup():
    print("Do cleanup ...")

timeout = Timeout(seconds=5, exception=TimeoutError)
try:
    target_function(20)
except TimeoutError:
    cleanup()
finally:
    print("Timeout ...")
    timeout.cancel()

I hope it meets your requirements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM