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()
您将在
datetime
模块中找到许多有用的函数:请注意,当调用
do_my_thing()
时,它实际上是在time_to_round
中的精确时间之后,因为计算机显然不能在精确的零时间内工作。不过,保证不会在那之前醒来。如果要引用do_my_thing()
中的“当前时间”,请传入time_rounded
变量,以便在日志文件中获得整洁的时间戳在上面的代码中,我故意每次重新计算
time_to_wait
,而不是在第一次计算后将其设置为5分钟。这就是为什么我刚才提到的轻微延迟不会在你运行脚本很长时间后逐渐滚雪球使用cronjob,对于raspberry pi,使用crontab https://www.raspberrypi.org/documentation/linux/usage/cron.md
相关问题 更多 >
编程相关推荐