timers not canceling!

A

Alex Hall

Hi all,
I am having trouble with a timer I am trying to use. It is the same
timer, but I need to cancel it when a certain event happens, then
start it again when a second event happens. The below is from a shell
session, not a file, but it shows my problem: I call cancel on a
timer, then call start on it, and it thinks it is already running?
What am I missing?
.... print("Time up!")
....Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\python26\lib\threading.py", line 465, in start
raise RuntimeError("thread already started")
RuntimeError: thread already started
I typed start, then typed cancel within ten seconds (probably four or
five), then called start again a couple seconds later. I figured
canceling the timer would kill the thread so I could start it again. I
am not looking for a reset, since I do not want it counting always.
Thanks.
 
S

Steven D'Aprano

Hi all,
I am having trouble with a timer I am trying to use. It is the same
timer, but I need to cancel it when a certain event happens, then start
it again when a second event happens. The below is from a shell session,
not a file, but it shows my problem: I call cancel on a timer, then call
start on it, and it thinks it is already running? What am I missing?

... print("Time up!")
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\python26\lib\threading.py", line 465, in start
raise RuntimeError("thread already started")
RuntimeError: thread already started


The start method is to start generic threads, not just timers, and
threads don't support being restarted.

Timers are fairly simple objects: after you start the thread, they just
wait until the time expires, then run a function. You can cancel them,
but not pause and restart them.

To do what you are trying to do, you will need to subclass either Timer
or thread and implement your own logic for pausing or restarting the
count down.

I typed start, then typed cancel within ten seconds (probably four or
five), then called start again a couple seconds later. I figured
canceling the timer would kill the thread so I could start it again.


That's not how they work. "start" means "start the thread", not "start
the timer", and threads cannot be restarted.

The documentation is very clear:

"start()
Start the thread’s activity.

It must be called at most once per thread object. It arranges for the
object’s run() method to be invoked in a separate thread of control."

http://docs.python.org/library/threading.html#thread-objects
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top