【问题标题】:write python script that is executed every 5 minutes编写每5分钟执行一次的python脚本
【发布时间】:2023-04-04 06:10:01
【问题描述】:

我需要编写一个在启动时自动启动并在树莓派上每 5 分钟执行一次的 Python 脚本。如何才能做到这一点?特别是,我怎样才能避免让脚本锁定 cpu 运行 infine 循环等待 5 分钟结束?

【问题讨论】:

  • 使用 cron,但 gevent 也能很好地完成任务或休眠

标签: python timer autostart


【解决方案1】:

您可以轻松地使用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

您可能希望将脚本的 stdout/stderr 重定向到文件,以便检查一切是否正常。这和shell一样,只是在脚本路径后面加上>>/var/log/<any-name>-info.log 2>>/var/log/<any-name>-error.log之类的东西。

【讨论】:

  • 谢谢!您有关于如何在 raspbian 上进行设置的示例吗?
  • 这取决于您的 Raspberry 上的操作系统,它是 Raspberry 而不是 PC 无关紧要。然而,它在所有 Linux 发行版上基本相同。我已经更新了我的答案,希望对您有所帮助。
  • 啊,Raspbian 实际上是一个发行版,不是 Raspberry Pi 的简称。 :)
  • 谢谢!无论如何,在 raspbian 上都禁用了 root .. :) 如果我需要通过我的脚本重新启动怎么办?它不适用于其他用户..
  • 那么你只需从脚本中运行sudo reboot...?
【解决方案2】:

您可以使用time.sleep

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      我认为您的代码需要不到 5 分钟,但每次运行的执行时间不是恒定的。

      import time
      
      while True:
        t= time.time()
      
        # your code goes here
      ................
      ........
        
        t= time.time()-t
        time.sleep(300-t)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-21
        • 2011-07-20
        • 2014-03-25
        • 1970-01-01
        相关资源
        最近更新 更多