crontab如果没有运行则运行python文件

Dee*_*sad 5 python crontab

我想通过crontab执行我的python文件,只要它已经关闭或没有运行.我尝试在cron选项卡中添加以下条目,但它不起作用

24 07 * * * pgrep -f test.py || nohup python /home/dp/script/test.py & > /var/tmp/test.out
Run Code Online (Sandbox Code Playgroud)

如果我pgrep -f test.py || nohup python /home/dp/script/test.py & > /var/tmp/test.out手动运行test.py工作正常 ,如果我删除pgrep -f test.py ||它也适用于crontab 从我的crontab,只是保持24 07 * * * nohup python /home/dp/script/test.py & > /var/tmp/test.out

如果我添加pgrep -f,任何想法为什么crontab不起作用?有没有其他方法我可以运行test.py一次,以避免test.py的多个运行进程?谢谢,迪帕克

Jac*_*ijm 5

从 cron 运行时 pgrep -f 将自身列为错误匹配

我通过script.py运行无限循环进行了测试。然后

pgrep -f script.py
Run Code Online (Sandbox Code Playgroud)

...从终端,在从 cron 运行时给出了一个pid, 13132

pgrep -f script.py > /path/to/out.txt
Run Code Online (Sandbox Code Playgroud)

输出两个pid,1313213635

因此,我们可以得出结论pgrep -f script.py,当从 cron 运行时,该命令将自身列为匹配项。不确定如何以及为什么,但最有可能的是,这是由cron使用一组非常有限的环境变量(HOME、LOGNAME 和 SHELL)运行的事实间接引起的。

解决方案

pgrep -f从(包装器)脚本运行会使命令列出自身,即使从cron. 随后,从cron以下位置运行包装器:

#!/bin/bash

if ! pgrep -f 'test.py'
then
    nohup python /home/dp/script/test.py & > /var/tmp/test.out
# run the test, remove the two lines below afterwards
else
    echo "running" > ~/out_test.txt
fi
Run Code Online (Sandbox Code Playgroud)