How to terminate the function that runs every n seconds

Dave Angel davea at
Wed Jan 14 17:33:31 CET 2015

On 01/14/2015 08:09 AM, Ganesh Pal wrote:
> Corrected Typos .
>> a) How to I prevent the execution  of   Print "EXECUTED SLEEP" after 4
>> seconds ? , current this is running in an infinite loop

Please on't top-post.  If you want to comment on a message, insert your 
comments after the portion of the message you'd like to comment on.

> On Wed, Jan 14, 2015 at 6:37 PM, Ganesh Pal <ganesh1pal at> wrote:
>> Iam using Linux and  Python 2.7  and playing with the threading.Timer module.
>> I had the below question on the same.
>> (a) How to I prevent the execution  the  "EXECUTED SLEEP" after 4
>> seconds ? , current this is running in an infinite loop
>> node-1# cat
>> import threading
>> import time
>> def printit():
>>          threading.Timer(2, printit).start()
>>          print "EXECUTED SLEEP"
>> printit()
>> print "hi"
>> time.sleep(4)
>> print "hi"
>> time.sleep(5)
>> Output:
>> node-1# python
>> hi

Do you want to fix the symptom, fix the problem, or finish a school 
assignment?  To do the first, make a global variable that contains the 
time you want to stop making new threads, and conditionally test it 
before calling threading.Timer

Something like
    quit_time = timer.time() + 4

If you want to fix the problem, consider that creating a new thread for 
each iteration is overkill, and consider how you might better solve it. 
  For example a single thread that loops through a range, and prints 
once each time could easily do something a fixed number of times.

if you want to get the homework done, better reread the assignment.  For 
example, if you just want to print the string a fixed number of times 
with a delay each time, you don't need threads at all.  But the 
assignment may have specified that you're stuck with using threads for 
the purpose, and it may have even required that you use Timer somewhere.

Note that neither Timer nor sleep makes any promises about how 
accurately it matches the requested time.


More information about the Python-list mailing list