Crontab 不会运行命令 @reboot

Crontab 不会运行命令 @reboot

我在服务器上运行 jupyter noteboook。

为了启动它,我有以下脚本:

#!/bin/sh
exec &> /home/user/logfile2.txt

echo 'running jup.sh' >> /home/user/logfile2.txt

cd /home/user/jup
unset XDG_RUNTIME_DIR
pipenv run jupyter notebook &

我的sudo crontab文件如下所示:

@reboot sleep 20 && /usr/scripts/jup.sh

它看起来也像这样:

@reboot sleep 20 && /usr/scripts/jup.sh &    -or-
@reboot sleep 20 && /home/user/jup.sh &      -or- 
@reboot (sleep 20 && /usr/scripts/jup.sh) > /dev/null 

脚本将输出文件的文件回显部分,并且我还回显了工作目录。据我所知,唯一没有执行的是“pipenv ...”命令。

  1. 我最近从 17.10 升级到了 18.04 LTS。它以前是在“常规”crontab 下而不是 sudo 下工作的。
  2. 该脚本将在 shell 上启动 jupyter 笔记本。

编辑1: 我实施了建议,为 pipenv 和 添加了完整路径. /etc/profile。但都没有解决问题。

我还删除了脚本的第一行,然后收到一封邮件,说找不到完整路径。它说需要完整路径。我添加了完整路径,错误就消失了。因此,完整路径是我的问题的一部分。

我有一个类似的脚本,它为 django 应用运行 gunicorn 服务器。它也可以在 shell 中运行,但不能在 @reboot 中运行。它也曾经与 @reboot 一起使用。

编辑2: 收到有关错误的电子邮件:(已通过添加路径修复此问题)

From [email protected]  Thu Jun 13 11:25:23 2019
Return-Path: <[email protected]>
X-Original-To: root
Delivered-To: [email protected]
Received: by experiments.local (Postfix, from userid 0)
    id 05966E144D; Thu, 13 Jun 2019 11:25:23 -0700 (PDT)
From: [email protected] (Cron Daemon)
To: [email protected]
Subject: Cron <root@experiments> (sleep 20 && /usr/scripts/jup.sh)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/root>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=root>
Message-Id: <[email protected]>
Date: Thu, 13 Jun 2019 11:25:23 -0700 (PDT)

/usr/scripts/jup.sh: 13: /usr/scripts/jup.sh: pipenv: not found

当前脚本:

#!/bin/sh
. /etc/profile

#exec &> /home/john/logfile2.txt

echo 'running jup.sh' >> /home/john/logfile2.txt

cd /home/john/jup
echo $PWD >> /home/john/logfile2.txt


unset XDG_RUNTIME_DIR
/usr/local/bin/pipenv run jupyter notebook &

juypter 是一个用于代码探索的 IDE。jupyter.org。我按照此处的说明安装了它:https://jupyterlab.readthedocs.io/en/stable/getting_started/installation.html

Root:我在 sudo crontab 和常规 crontab 中都运行过它。在过去几天之前,它不是以 root 身份运行。作为故障排除的一部分,我在两种情况下都运行了该脚本,以查看是否有区别。结果没有。

答案1

当脚本由 cron 执行时,通常不会像登录 shell 那样设置环境变量。特别PATH是缺少,这意味着 shell 找不到命令pipenv。可能的解决方案:

  1. 添加外部命令的绝对路径。您可以pipenv使用

    $ which pipenv
    

    最后,脚本中的调用应该类似于

    /usr/bin/pipenv run jupyter notebook &
    
  2. 加载完整的环境。这通常通过在脚本顶部添加以下行来实现:

    . /etc/profile
    

相关内容