编写Python脚本,每隔5分钟执行一次。

7

我需要编写一段 Python 脚本,在 Raspberry Pi 上启动时自动开始运行,并且每 5 分钟执行一次。如何实现此功能?特别是,如何避免脚本在等待 5 分钟结束时锁定 CPU 并运行无限循环。


使用cron,但gevent也可以很好地完成任务或者sleep。 - Paul
4个回答

21

您可以轻松使用Cron来安排运行Python脚本的任务。;)

如何设置Cron

我假设您已经安装了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的内容即可。


谢谢!你有在Raspbian上设置它的示例吗? - user2452250
这取决于您在树莓派上使用的操作系统,与其不是PC无关。但是,在所有Linux发行版上基本上都是相同的。我已经更新了我的答案,希望能有所帮助。 - Jakub Jirutka
啊,Raspbian实际上是一个发行版,而不是树莓派的缩写。 :) - Jakub Jirutka
那么你只需要从脚本中运行 sudo reboot 命令,是吗? - Jakub Jirutka
当然,cron是一个守护进程,你应该将它添加到运行级别中,在启动后自动启动。 - Jakub Jirutka
显示剩余3条评论

8

使用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)

3
你可以使用 time.sleep
count = -1
while(not abort):
    count = (count+1) % 100
    if count == 0:
        print('hello world!')
    time.sleep(3)

2
我考虑你的代码需要不到5分钟,但每次运行的执行时间不是恒定的。
import time

while True:
  t= time.time()

  # your code goes here
................
........
  
  t= time.time()-t
  time.sleep(300-t)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接