How to run a repeating timer every n minutes?

Diez B. Roggisch deets at nospam.web.de
Thu Oct 29 12:15:31 EDT 2009


mk wrote:

> Frank Millman wrote:
> 
>> class Timer(threading.Thread):
>>     def __init__(self):
>>         threading.Thread.__init__(self)
>>         self.event = threading.Event()
>> 
>>     def run(self):
>>         while not self.event.is_set():
>>              """ The things I want to do go here. """
>>              self.event.wait(number_of_seconds_to_wait)
>> 
>>     def stop(self):
>>         self.event.set()
>> 
>> In your main program -
>>   - to start the timer
>>       tmr = Timer()
>>       tmr.start()
>> 
>>   - to stop the timer
>>       tmr.stop()
>> 
>> It is easy to extend this by passing the number_of_seconds_to_wait, or a
>> function name to be executed, as arguments to the Timer.
> 
> I'm newbie at threading, so I'm actually asking: should not method like
> stop() be surrounded with acquire() and release() of some threading.lock?
> 
> I mean, is this safe to update running thread's data from the main
> thread without lock?

stop() is part of the Timer-interface, and tas it's not mentioned to be
unsafe in the docs you can just call it. It might be that it internally
calls some threadsafe means of communication (Event, Lock).

In general you are right, however many of those considerations don't apply
to (C)Python due to the GIL (global interpreter lock), which ensures that a
lot of operations are atomic. For example, in current CPython it's
perfectly safe to simply set a boolean instance variable to False to stop
an running loop.

Diez



More information about the Python-list mailing list