【问题标题】:How to run a shell script once a day?如何每天运行一次 shell 脚本?
【发布时间】:2015-05-26 17:15:30
【问题描述】:

我试图每天只运行一次这个特定的 shell 脚本。这是我的runLucene.py 代码:

#!/usr/bin/env python

import os
from extras.download_datos_desambiguar import news_Lucene

x=datetime.today()
y=x.replace(day=x.day, hour=09, minute=00, second=0, microsecond=0)
delta_t=y-x

secs=delta_t.seconds+1

def fourdlife():
    print "checking function"
    os.system("~/code/4dlife_repo/4dbatch/src/engines/extras/download_datos_desambiguar/news_Lucene.py")



t = Timer(secs, fourdlife)
t.start()
print "timer started"

我正在我的ProcesosContinuous.py 文件中运行此代码,如下所示:

while True:
            os.system("./runl.sh")
            #some other processes

runl.sh 在哪里

python ~/code/4dlife_repo/4dbatch/src/engines/extras/download_datos_desambiguar/news_Lucene.py

这个 python 代码总是在我的apache2 服务器上运行。

但是,这适用于任何给定时间,而不仅仅是指定时间。我究竟做错了什么? 另外,我觉得有更好的方法来做到这一点。我查看了cron 任务,但这不是我想要的。我不希望我的程序转到sleep(),因为我需要在runl.sh 进程之后运行其他进程。最好的方法是什么?

【问题讨论】:

  • 您能解释一下为什么cron 对您不利吗?这正是它的目的。
  • 因为我在某个地方读到过,这和把代码放到sleep() 直到下一次它应该运行是一样的。
  • @eugene,我正在从我的 python 代码中调用 shell 脚本。请在评论前仔细阅读问题。
  • 仔细阅读:“这是我的runl.sh代码:”这里是python代码。那么?
  • “Somewhere”不是一个好的技术来源。 cron 有一个后台程序,它在后台运行并执行预定的作业。只有以这种方式设计,作业才会进入休眠状态。至于你的另一句话,这句话与第二个sn-p有关。问题是这样写的。如果您还有其他意思 - 欢迎您对其进行编辑。

标签: python linux bash shell


【解决方案1】:

crontab -e 命令将打开一个交互式编辑器,您可以在其中定义一个 cron 作业。

在该编辑器的缓冲区中,您可以输入如下一行(然后保存):

00 00 * * * /path/to/script.sh

此命令将在每个午夜运行script.sh

【讨论】:

  • 它说 .sh:1 :17 : not found.
  • p=subprocess.call("00 00 * * * lrunl.sh",shell=True)
  • /bin/sh : 1: 00 未找到。
  • @kaushaya,以00 开头的字符串是应该放在crontab 文件中的内容,而不是自己运行的命令。 (此外,作为一般规则,不要在没有充分理由的情况下使用 shell=True;它会为您打开本来可以避免的整个类的错误 [shell 注入、shellshock 等])。
  • @kaushaya,我假设您正在尝试编写配置 crontab 的 Python 代码;它是否正确?这里的答案是假设手动过程编写的。你有理由希望它是 Python 吗?可以接受 shell 脚本吗?
【解决方案2】:

cron 一直在做它的事情,我认为使用它比使用一个专门用于不断检查是否该运行 shell 脚本的 python 脚本要好得多。

话虽如此,当您创建 crontab 时,它将位于用户 crontab 下,因此只需观察用户和/或 -u 它。

【讨论】:

  • 你能帮忙写一些代码吗?出于某种原因,我发现 cron 相当具有挑战性。
  • 我正在添加这个59 15 * * * /bin/sh /code/4dlife_repo/4dbatch/src/engines/runl.sh,但它仍然无法正常工作。我尝试通过 `59 15 * * * /bin/sh /code/4dlife_repo/4dbatch/src/engines/runl.sh > printoutput.txt" 查看输出,但仍然没有。
  • chmod +x /code/blah/blah/blah/run1.sh 并摆脱 /bin/sh
  • 照做了,还是没有运气。
  • @kaushaya 你能从 shell 运行它吗? crontab -l 说什么? head -n 10 run1.sh 说什么?
最近更新 更多