【问题标题】:Run python script every 5 minutes on the clock在时钟上每 5 分钟运行一次 python 脚本
【发布时间】:2020-02-12 21:32:02
【问题描述】:
我正忙于在树莓派上编写用于雨量计的 python 脚本。
该脚本需要计算桶的尖端,并每 5 分钟将总降雨量写入 csv 文件。该脚本现在每 299.9 秒写入一次,但我希望它每隔 5 分钟写入一次,例如:14:00、14:05、14:10 等等。
有没有人可以帮帮我?
提前致谢!
【问题讨论】:
标签:
python
raspberry-pi
gauge
【解决方案2】:
datetime 模块中有很多有用的功能:
from datetime import datetime, timedelta
# Bootstrap by getting the most recent time that had minutes as a multiple of 5
time_now = datetime.utcnow() # Or .now() for local time
prev_minute = time_now.minute - (time_now.minute % 5)
time_rounded = time_now.replace(minute=prev_minute, second=0, microsecond=0)
while True:
# Wait until next 5 minute time
time_rounded += timedelta(minutes=5)
time_to_wait = (time_rounded - datetime.utcnow()).total_seconds()
time.sleep(time_to_wait)
# Now do whatever you want
do_my_thing()
请注意,当调用do_my_thing() 时,它实际上会在time_to_round 中的确切时间之后的一小部分,因为显然计算机无法在零时间内完成工作。不过可以保证在此之前不会醒来。如果您想引用do_my_thing() 中的“当前时间”,请传入time_rounded 变量,以便在日志文件中获得整洁的时间戳。
在上面的代码中,我故意每次都重新计算time_to_wait,而不是在第一次之后将其设置为 5 分钟。这样一来,我刚才提到的轻微延迟不会在您运行脚本很长时间后逐渐滚雪球。