0

In Python, if I do something like the answer in this thread: Executing periodic actions in Python

eg:

>>>import time, threading
>>> def foo():
...   print(time.ctime())
...   threading.Timer(10, foo).start()
...
>>> foo()

I understand that each 10 seconds I'm starting a new Timer thread that will wait the time, then create a new timer, etc, and it will run indefinitely.

Obviously, there is nothing in the output of dir() as I didn't assign it a name.

Is there any way to get a reference to this Timer, for instance to .cancel() it? Or is the only way to stop it to have kept a reference to it from the beginning?

I know this is very poor practice, but it demonstrates my more general question.

Community
  • 1
  • 1
nexus_2006
  • 744
  • 2
  • 14
  • 29

1 Answers1

0

Timers are a Thread subclass, and like all Threads, they show up in enumeration. You wouldn't necessarily know which one is the timer, but you can get a list of all running threads with threading.enumerate().

If you just want to cancel all outstanding Timers, you could do:

for thread in threading.enumerate():
    if isinstance(thread, threading._Timer):  # In Py2.7 at least, Timer is a function wrapping the class _Timer
        thread.cancel()

Obviously, this would be playing unsportingly if your code is just one library among many, since it would cancel Timers spawned elsewhere; not cricket that.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271