Search code examples
pythonhtmlpython-multithreadingmechanize-python

Thread timer issues python


I am trying to use the thread.Timer class, but I keep getting crashes. Here is the idea : i have a code that launches an optimisation on a web application. When the optimisation is launched, i want to send periodic requests to the web app server to know if the optimisation is finished, or still executing.

def checkPeriodically(self):
    print "Sending a request"
    finished = self.checkOptim()
    if finished :
        return
    t = threading.Timer(60,self.checkPeriodically)
    t.start()

My checkOptim function uses mechanize to connect to the application and read the result page ; then it uses an HTMLParser to check whether the optimisation is finished or not.

def checkOptim(self):
    browser = mechanize.Browser()
    browser.set_handle_refresh(True, honor_time=True, max_time=10) 
    browser.open('resultPageURL')
    response = browser.response().read()
    parser = MyHTMLParser(self.optimName)
    parser.feed(response)
    return parser.optimFinished

All of this is part of a plugin i am writing for QGIS (a GIS), but I do not think the problem is related to the software, it is probably due to me not using the threading class properly. Any help would be deeply appreciated.


Solution

  • I do not know what is the error message you've got, but it might be that the object that function checkPeriodically is part of it doesn't exists anymore.

    Here example of working code: (I"m keeping reference to the object until all jobs are done).

    import threading
    import time
    
    class cls:
        def __init__(self):
            pass
            self.stop_if_zero = -10
    
        def checkPeriodically(self):
            print "Sending a request %s" % self.stop_if_zero
            self.stop_if_zero +=1;
            if 0 == self.stop_if_zero :
                return
            t = threading.Timer(2,self.checkPeriodically)
            t.start()    
    
    #create instance of the class
    st = cls()
    #start the thread with timer
    st.checkPeriodically();
    
    while (0 > st.stop_if_zero ):
        # keep referance to ST untill it ends or else it might crashed.
        time.sleep (0.1);