Stopping a third party function

后端 未结 2 1536
遇见更好的自我
遇见更好的自我 2021-01-27 04:56

This is part of a complex project, I will try and simplify it.

I have a class that gets a callable and executes it, the callable can run for any duration of time. If I

2条回答
  •  清酒与你
    2021-01-27 05:08

    If anyone ever needs this here is a code sample of it working (One thing to note signal.signal can be called only from the main thread):

    #!/usr/bin/python
    import time
    import signal
    import threading
    
    
    class MyException(Exception):
        pass
    
    
    class FooRunner(object):
        def goo(self, foo):
            try:
                signal.signal(signal.SIGALRM, self.on_stop_signal)
                foo()
            except MyException:
                print('caugt alarm exception')
    
        def on_stop_signal(self, *args):
            print('alarm triggered')
            raise MyException()
    
    
    def sample_foo():
        time.sleep(30)
    
    
    def stop_it():
        signal.alarm(3)
        print('alarm was set for 3 seconds')
    
    
    if __name__ == "__main__":
        print('starting')
        fr = FooRunner()
        t = threading.Thread(target=stop_it)
        t.start()
        fr.goo(sample_foo)
    

    Thanks @jsbueno

提交回复
热议问题