Jonathan Shan wrote:
Hello,
I am trying to call a function every 5 seconds. My understanding of
time.sleep() is during the sleep time everything "stops". However, in
my application, there are background processes that must be running
continuously during the five second interval. Thus, threading.Timer
seems like a good function. Here is the relevant code:
# background processes
t = threading.Timer(5.0, function_name, [arguments])
while True:
# Do background processes run inside while loop?
t.start()
The above code generates an error:
AssertionError: thread already started
Any hints on how to fix the error? Also, do background processes run
inside while loops?
Thanks in advance,
Jonathan Shan
Here's a little thread-test program I wrote a few years ago. I hope it
will explain how threads and sleeps interact.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------
import time, threading, random
class MyThread(threading.Thread):
""" Each thread picks a 'random' integer between 0 and 19 and reports
in once per second for that many seconds.
"""
def run(self):
iterations = random.randint(0, 19)
print "Thread", self.getName(), "starting", iterations, "iterations"
for i in range(iterations):
print " ", self.getName(), "is reporting "
time.sleep(1)
print self.getName(), "is DONE"
def test():
threadList = []
iterCount = 0
# Create 5 MyThread() threads
for i in range(5) :
thread = MyThread()
threadList.append(thread)
# Start all threads
for thread in threadList:
thread.start()
# As long as we have more than just the 'main' thread running, print out
# a status message
while threading.activeCount() > 1 :
print "-- after", iterCount, "sleeps", \
str(threading.activeCount()), "threads running including main"
iterCount += 1
time.sleep(1)
print "Only main thread remains"
if __name__ == '__main__':
test()
--
http://mail.python.org/mailman/listinfo/python-list