每5分钟运行一次python脚本

2024-05-21 04:26:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正忙着在树莓圆周率上为雨量计编写python脚本。 脚本需要计算桶尖,并将每5分钟的总降雨量写入csv文件。脚本现在每299.9秒写一次,但我希望它每5分钟写一次,例如:14:00、14:05、14:10等等

有人能帮我吗

提前谢谢


Tags: 文件csv脚本树莓降雨量圆周率雨量计
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分钟。这就是为什么我刚才提到的轻微延迟不会在你运行脚本很长时间后逐渐滚雪球

使用cronjob,对于raspberry pi,使用crontab https://www.raspberrypi.org/documentation/linux/usage/cron.md

相关问题 更多 >