简体   繁体   English

列出所有活动的多线程.Timer对象

[英]List all active multithreading.Timer objects

Is there a way to obtain a list of all the active threading.Timer objects in order to cancel all of them before exiting? 有没有办法获取所有活动的threading.Timer对象的列表,以便在退出之前cancel所有这些对象? Otherwise the program hangs to wait their completion. 否则程序会挂起以等待完成。

I could keep a list of them, but then I also have to remove them when they fire. 我可以保留它们的列表,但是当它们发射时我也必须将它们移除。 Instead I wanted to know if there was a way to obtain all of them. 相反,我想知道是否有办法获得所有这些。

threading.enumerate() returns a list that will include Timers that are Alive - they are instances of threading._Timer . threading.enumerate()返回一个列表,其中包含Alive的 Timers - 它们是threading._Timer实例。

>>> t = threading.Timer(30, foo, kwargs = d)
>>> t.start()
>>> t.isAlive()
True
>>> for thing in threading.enumerate():
    if isinstance(thing, threading._Timer):
        thing.cancel()


>>> t.isAlive()
False
>>> 

If you just need to cancel the timers when exiting from the program, you can set the daemon flag for the timers and they will be killed on exit instead of waiting for their completion: 如果您只需要在退出程序时取消计时器,则可以为计时器设置daemon标志,它们将在退出时被终止而不是等待它们完成:

from threading import Timer
timer = Timer(10, fn)
timer.setDaemon(True)
timer.start()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM