sleep and Timer

Rob Hall robhall at ii.net
Wed May 28 11:34:18 EDT 2003


I have a thread which needs to download a web page and process it
periodically (every couple of minutes).  Up until now, in the thread I have
had something like this:

def run(self):
    while self.quit = false:
        DO SOME STUFF
        time.sleep(120)

def quit(self):
    self.quit = 1

This allows me to abort the thread if needed.

However, if the sleep() has just been called, it can take 120 seconds for
the thread to die.  I want it to die immediately.

So I tried throwing it a signal as per the module docs, but for the life of
me, could not get it to work.

Can someone throw some light on the subject for me?


Also, I have some confusion with isAlive()

I tried implementing a similar idea using threading.Timer as follows:

import time
import threading
import signal
import thread

class test(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.t=threading.Timer(4, self.main)

    def run(self):
        print '                >>>> Thread launched'
        self.t.start()
        #self.t.join()

    def main(self):
        print '                >>>> Sleeping'
        self.t=threading.Timer(2, self.main)
        self.t.start()

    def quit(self):
        print '                >>>> Exiting.'
        self.t.cancel()



a = test()
a.start()

print 'Sleeping for X seconds'
count = 0
while count < 10:
    if a.isAlive():
        print 'a is alive'
    else:
        print 'a is dead'
    count += 1
    time.sleep(1)


print 'Interupting thread'
a.quit()

print 'Wake again'
a.main()
print 'Main sleeping again'
count = 0


while count < 10:
    if a.isAlive():
        print 'a is alive'
    else:
        print 'a is dead'
    count += 1
    time.sleep(1)
print 'interupt again'
a.quit()


count = 0
while count < 10:
    if a.isAlive():
        print 'a is alive'
    else:
        print 'a is dead'
    count += 1
    time.sleep(1)

a.join()

print 'finished program'


Yes it is messy I know - sorry...

The concept works well for my program except that it will ALWAY report
istelf as NOT alive!  This is because the run method terminates, even though
the Timer object is still running.

Now, why doesn't Python deny access to its methods when the process has
declared itself dead?  Is it OK to structure my program like this?  Is there
a better way?

Thanks in advance.

Rob






More information about the Python-list mailing list