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

标签 python timer autostart

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

最佳答案

您可以轻松使用 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 的内容在脚本路径之后。

关于python - 编写每 5 分钟执行一次的 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21648410/

相关文章:

python - 无法使用 python-uinput 将触摸事件写入 uinput

python - 如何在python中使用selenium查找html类中是否存在元素

java - 倒数计时器在手机关闭或应用程序被杀死时仍然运行

shell - 在 Ubuntu 中调试/etc/init.d 启动脚本

python - 黑客排名 : Check Binary Search Tree: Python -test case -for duplications

python - 如何正确地包含与 python 拟合的不确定性

c++ - 通过引用传递与通过指针传递 : Boost threads and deadline timer

c - 多媒体计时器在 Release模式下工作正常,但在 Debug模式下工作不正常

service - 这是服务的实际用途吗?

linux - 系统启动后应用程序自动启动 Linux 中的随机时间间隔