Python定时器模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20887563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Timer module
提问by
I found this snippet of code somewhere:
我在某处找到了这段代码:
t = Timer(10.0, hello)
t.start()
Where 10.0 is the time in seconds for when the timer is supposed to execute, and hello is the method that will run when the time parameter is met. However, I can't find the module this function belongs to. Any help?
其中 10.0 是计时器应该执行的时间(以秒为单位),hello 是满足时间参数时将运行的方法。但是,我找不到此功能所属的模块。有什么帮助吗?
回答by
回答by MattDMo
Timer()is a class in the threadingmodule:
Timer()是threading模块中的一个类:
This class represents an action that should be run only after a certain amount of time has passed — a timer. Timer is a subclass of Thread and as such also functions as an example of creating custom threads.
Timers are started, as with threads, by calling their
start()method. The timer can be stopped (before its action has begun) by calling thecancel()method. The interval the timer will wait before executing its action may not be exactly the same as the interval specified by the user.
这个类代表一个只有在经过一定时间后才应该运行的动作——一个计时器。Timer 是 Thread 的子类,因此也可以作为创建自定义线程的示例。
定时器和线程一样,通过调用它们的
start()方法来启动。可以通过调用该cancel()方法来停止计时器(在其操作开始之前)。计时器在执行其操作之前将等待的时间间隔可能与用户指定的时间间隔不完全相同。
回答by Ammar Hasan
This depends on your code logic. But from the code supplied, most probably it is Timer from threading module, so you just have to add this at the top of your code
这取决于您的代码逻辑。但是从提供的代码来看,很可能是线程模块中的 Timer,因此您只需将其添加到代码的顶部
from threading import Timer
Documentation is here: threading.Timer
文档在这里:threading.Timer
回答by MadPhysicist
Even though this is probably not the case here given the context, it is also possible that the Timer is from the timeit module which allows to run tests on the quickness of execution.
尽管鉴于上下文可能不是这种情况,但 Timer 也可能来自 timeit 模块,该模块允许对执行速度进行测试。
That is, from timeit import Timer
那是, from timeit import Timer

