python3 定时器的使用
时间: 2023-12-03 16:55:12 浏览: 22
在Python3中,可以使用`Timer`类来创建定时器。该类位于`threading`模块中,可以在指定的时间后执行一个函数。
下面是一个简单的示例,演示如何使用定时器执行一个函数:
```python
import threading
def hello():
print("Hello, world!")
# 创建一个定时器,2秒后执行hello函数
t = threading.Timer(2.0, hello)
t.start()
```
上述代码将在2秒后输出"Hello, world!"。
如果需要取消定时器,可以使用`cancel`方法:
```python
t.cancel() # 取消定时器
```
注意,如果定时器已经开始执行,调用`cancel`方法并不能马上停止执行,而是要等待函数执行完毕后才能停止。如果需要立即停止执行,可以在函数中添加一个标志,通过设置该标志来终止函数的执行。例如:
```python
import threading
def hello():
global stop_flag
if stop_flag:
return
print("Hello, world!")
t = threading.Timer(2.0, hello)
t.start()
stop_flag = False
# 创建一个定时器,2秒后执行hello函数
t = threading.Timer(2.0, hello)
t.start()
# 10秒后停止定时器
timer = threading.Timer(10.0, lambda: setattr(globals(), 'stop_flag', True))
timer.start()
```
上述代码将在2秒后输出"Hello, world!",然后每隔2秒输出一次,直到10秒后停止。这里使用了一个全局变量`stop_flag`来控制函数的执行。定时器的停止通过另一个定时器实现,10秒后设置`stop_flag`为`True`,让函数自然地停止。