[英]Run python script every 5 minutes on the clock
I'm busy with an python script on a raspberry pi for a rain gauge.我正忙于在树莓派上编写一个用于雨量计的 Python 脚本。 The script need to count the tips of the bucket and write the total rain amount every 5 minutes to a csv file.
该脚本需要计算水桶的尖端并将每 5 分钟的总降雨量写入一个 csv 文件。 The script does the writing now every 299.9 seconds but I want it to write every exact 5 minutes, for example: 14:00, 14:05, 14:10 and so on.
该脚本现在每 299.9 秒写入一次,但我希望它每 5 分钟写入一次,例如:14:00、14:05、14:10 等等。
Is there anyone who could help me out?有没有人可以帮助我?
Thanks in advance!提前致谢!
使用 cronjob,对于树莓派,使用 crontab https://www.raspberrypi.org/documentation/linux/usage/cron.md
You will find lots of helpful functions in the datetime
module:您会在
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()
Note that when do_my_thing()
is called it will actually be fractionally after the exact time in time_to_round
, because obviously computers can't do work in precisely zero time.请注意,当
do_my_thing()
被调用时,它实际上会在time_to_round
的确切时间之后time_to_round
,因为显然计算机不能在精确的零时间内工作。 It's guaranteed not to wake up before that time though.不过保证在那个时间之前不会醒来。 If you want to refer to the "current time" in
do_my_thing()
, pass in the time_rounded
variable so that you get neat timestamps in your log file.如果要在
do_my_thing()
引用“当前时间”,请传入time_rounded
变量,以便在日志文件中获得整洁的时间戳。
In the code above I've deliberately recomputed time_to_wait
each time, rather than just setting it to 5 minutes after the first time.在上面的代码中,我每次都特意重新计算
time_to_wait
,而不是第一次将其设置为 5 分钟后。 That's so that the slight delay I just mentioned don't gradually snowball after you've been running the script for a long time.这样我刚刚提到的轻微延迟不会在您运行脚本很长时间后逐渐滚雪球。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.