Luk*_*lic 5 python time while-loop python-datetime raspberry-pi
我有一个在 Raspberry Pi 上运行的程序,我想每 15 分钟在整点的 0、15、30 和 45 分钟从温度计中提取一些数据。
我已经使用 while 循环尝试过此操作,之前我有效地使用了 time.sleep(900),但有时会偏离整点后的 0、15、30 和 45 分钟。
目前我有这个;
from datetime import datetime
def run(condition):
while condition == True:
if (datetime.now().minute == (0 or 15 or 30 or 45)):
#perform some task
temperature_store()
Run Code Online (Sandbox Code Playgroud)
为简单起见,我没有深入了解Temperature_store() 的作用,但它从插入 Pi 的传感器读取温度,然后将其打印出来。
我希望Temperature_store() 每 15 分钟发生一次,但目前,它每秒发生一次。
我知道这可能是因为我的 while 循环的逻辑/语法错误,但我无法弄清楚。(对python脚本没有太多经验,耽误时间)。
有两种方法可以做到这一点:“简单”的方法和稳定的方法。
简单的方法就是执行以下操作:
from datetime import datetime
from time import sleep
def run(condition):
while datetime.now().minute not in {0, 15, 30, 45}: # Wait 1 second until we are synced up with the 'every 15 minutes' clock
sleep(1)
def task():
# Your task goes here
# Functionised because we need to call it twice
temperature_store()
task()
while condition == True:
sleep(60*15) # Wait for 15 minutes
task()
Run Code Online (Sandbox Code Playgroud)
这本质上会等到我们与正确的分钟同步,然后执行它,并在循环之前等待 15 分钟。如果您愿意,可以使用它,这是纯 Python 中最简单的方法。然而,这样做的问题是无数的:
第二种方法是使用cron-jobs,如评论中建议的那样。这是优越的,因为:
因此,使用起来很简单(假设您使用的是 Linux):
from crontab import CronTab
cron = CronTab(user='username') # Initialise a new CronTab instance
job = cron.new(command='python yourfile.py') # create a new task
job.minute.on(0, 15, 30, 45) # Define that it should be on every 0th, 15th, 30th and 45th minute
cron.write() # 'Start' the task (i.e trigger the cron-job, but through the Python library instead
Run Code Online (Sandbox Code Playgroud)
(显然,username适当配置)
在 中yourfile.py,在同一路径中,只需将temperature_store().
我希望这有帮助。显然,如果您愿意,可以使用第一种方法,甚至可以使用评论中的建议,但我只是觉得整个循环结构有点太脆弱了,尤其是在 Raspberry Pi 上。如果您想将其他物联网设备连接到您的 Pi,这应该是更稳定和可扩展的东西。