python 循环每次整点运行某个方法
时间: 2023-12-10 07:05:41 浏览: 38
您可以使用 Python 的 time 模块和 datetime 模块来实现每小时运行某个方法。具体步骤如下:
1. 导入 time 和 datetime 模块:
```python
import time
import datetime
```
2. 创建一个无限循环,使程序持续运行:
```python
while True:
```
3. 获取当前时间,并将分钟和秒数设置为 0,使其变成整点:
```python
now = datetime.datetime.now()
run_at = datetime.datetime(now.year, now.month, now.day, now.hour, 0, 0)
```
4. 如果当前时间等于设置的运行时间,则执行需要运行的方法:
```python
if now == run_at:
# 运行需要执行的方法
```
5. 在每次循环的结尾,使用 time.sleep() 方法暂停程序一段时间,以减少 CPU 负载:
```python
time.sleep(60) # 暂停程序一分钟
```
完整代码如下:
```python
import time
import datetime
def my_method():
# 需要每小时执行的方法
print("Method executed at:", datetime.datetime.now())
while True:
now = datetime.datetime.now()
run_at = datetime.datetime(now.year, now.month, now.day, now.hour, 0, 0)
if now == run_at:
my_method()
time.sleep(60)
```