Search code examples
pythonmultithreadingrestart

Restarting hanging threads


I have a script that runs but it has a tendency of hanging. I am trying to make another script to run it using threads, but the auto-restarting function does not seem to be working.

What I want this script to do is to restart the function every 900 seconds, or if it is possible, restart it whenever it hangs.

import time
import threading
import os

import functionname


def restart():
    time.sleep(900)
    os.execl('currentfilepath')

def res():
    while True:
        try:
            # do your works
            t = threading.Thread(target=restart, args=(), name='reset')
            t.start()
            functionname()
        except:
            print('error')
        finally:
            print('done')

if __name__ == '__main__':
    res()

Solution

  • so I managed to find a way to solve this.

    import multiprocessing
    import time
    
    t=600 #  time to wait
    
    def bar():
        # do stuff
    
    
    def barn():
        for i in range(t*500):  # runs for 500 times
            # print ("Tick"+str(i)+'n') # just for tracking progress
            time.sleep(1)
            if i % t == 0:
                print('restarting')
                p = multiprocessing.Process(target=bar)
                p.terminate
                p = multiprocessing.Process(target=bar)
                p.start()
    
    
    if __name__ == '__main__':
        p = multiprocessing.Process(target=bar)
        p.start()
        p1 = multiprocessing.Process(target=barn)
        p1.start()
    

    Probably not the most elegant but hey, it works.