我需要编写一段 Python 脚本,在 Raspberry Pi 上启动时自动开始运行,并且每 5 分钟执行一次。如何实现此功能?特别是,如何避免脚本在等待 5 分钟结束时锁定 CPU 并运行无限循环。
您可以轻松使用Cron来安排运行Python脚本的任务。;)
我假设您已经安装了Cron;如果没有,请安装一些(例如Vixie-Cron)。
创建一个名为/etc/cron.d/<any-name>.cron
的新文件,并使用以下内容:
# run script every 5 minutes
*/5 * * * * myuser python /path/to/script.py
# run script after system (re)boot
@reboot myuser python /path/to/script.py
在运行脚本的用户处填写myuser
(出于安全原因,如果可能的话,应该避免使用root)。如果这行不起作用,那么尝试将内容附加到/etc/crontab
中。
您可能希望将脚本的标准输出/标准错误重定向到文件,以便可以检查是否一切正常。这与shell中相同,只需在脚本路径后添加类似于>>/var/log/<any-name>-info.log 2>>/var/log/<any-name>-error.log
的内容即可。
sudo reboot
命令,是吗? - Jakub Jirutka使用schedule
import schedule
import time
def func():
print("this is python")
schedule.every(5).minutes.do(func)
while True:
schedule.run_pending()
time.sleep(1)
count = -1
while(not abort):
count = (count+1) % 100
if count == 0:
print('hello world!')
time.sleep(3)
import time
while True:
t= time.time()
# your code goes here
................
........
t= time.time()-t
time.sleep(300-t)