Steve wrote:
Hi All,

I've been trying to come up with a good way to run a certain process
at a timed interval (say every 5 mins) using the SLEEP command and a
semaphore flag. The basic thread loop was always sitting in the sleep
command and not able to be interrupted. When the time came to set the
semaphore flag to false (stopping the thread), my program would have
to wait up to the entire sleep time to break out of the loop.

I have finally found a very workable solution to break out of the
sleep loop by using a time slicing loop to divide the overall sleep
time into small pieces (slices) giving the loop more opportunities to
be interrupted.

A better approach for this is to use a Python Event or Condition object:
http://docs.python.org/library/threading.html#id5

Example code:


import threading
my_stop_event = threading.Event()

      # Sleep Loop :
      #for current_loop in range(0, self.time_slice) :
      #  time.sleep(self.sleep_time / self.time_slice)

      event.wait(self.sleep_time)
      if not self.running:    # check the flag
        break                 # break out of the sleep loop

# From another thread, you can notify the above sleeping thread using:
my_stop_event.set()


Cheers,
Todd
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to