timer problem

F

flupke

I have a timer in a program but the function it is supposed
to call, is only executed once.
To simplify searching what i have done wrong, i've made a small
test app
================================
import threading

def command():
print "TIMER CALLED"

t = threading.Timer(2, command )
t.start()
s = raw_input()
t.cancel()
================================
Now, when i run it, it only prints TIMER CALLED once instead
of every 2 seconds.
What am i doing wrong? (Python 2.3.4 on Win2000)

Thanks,
Benedict
 
D

Diez B. Roggisch

flupke said:
Now, when i run it, it only prints TIMER CALLED once instead
of every 2 seconds.
What am i doing wrong? (Python 2.3.4 on Win2000)


You assume that Timer is looping - it isn't. So make your command start a
Timer itself, like this:

def command():
print "called"
t = threading.Timer(2, command )
t.start()


Or use a Thread, with an endless loop in the run()-method that sleeps for
two secdonds. That spares you the overhead of thread-creation.

Regards,

Diez
 
F

flupke

Diez said:
You assume that Timer is looping - it isn't. So make your command start a
Timer itself, like this:

def command():
print "called"
t = threading.Timer(2, command )
t.start()

Or use a Thread, with an endless loop in the run()-method that sleeps for
two secdonds. That spares you the overhead of thread-creation.

Regards,

Diez

This method (calling the Timer again) indeed works but to effectively
cancel the thread then, i need to make the thread t a class object and
i need to define the command function as a real function as opposed to
an anonymous function (what i tried to do).
Then it might be a better sollution to indeed create my own Timer class.

Benedict
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,192
Latest member
KalaReid2

Latest Threads

Top