python固定时间间隔执行程序
时间: 2024-06-22 16:01:00 浏览: 7
在Python中,如果你想要定期执行一个程序或任务,你可以使用`time`模块和`threading`模块,特别是`threading.Timer`类,或者结合`schedule`库来实现定时任务。这里简单介绍一下两种方法:
1. **使用`threading.Timer`**:
```python
import threading
import time
def my_function():
# 你的代码逻辑
print("Function executed at a fixed interval")
# 设置定时器,例如每5秒执行一次
timer = threading.Timer(5.0, my_function)
timer.start()
# 如果你想让定时器在某个时间后停止,可以在`start()`后调用`cancel()`方法
```
2. **使用`schedule`库**(推荐,更灵活):
```python
from schedule import scheduled_job
import time
def job_function():
# 你的代码逻辑
print("Function executed at a fixed interval")
# 使用schedule装饰器指定定时任务
@scheduled_job('interval', minutes=1) # 每分钟执行一次
def scheduled_task():
job_function()
# 启动调度
scheduled_task.start()
```