编写每5分钟执行的python脚本

问题描述 投票:2回答:3

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

python timer autostart
3个回答
9
投票

您可以轻松地将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之类的内容。


4
投票

您可以使用time.sleep

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

0
投票

使用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)
© www.soinside.com 2019 - 2024. All rights reserved.